I'm trying to make a form where I can enter three values for a game (title, rating, and price) and save those values on submit and show the list underneath in a table. I am new to react and I got it working by using ref but I'm not sure if this is best practice. While googling for a solution, I saw many people use onChange to save the state as it's being typed even when there is a submit button. This is what I did but im not sure if this is best practice. Can I get some feedback? Thank you!
class App extends Component {
state = {
games: [{title:"Mario Kart", rating:7.4,price:"$45"}]
};
handleSubmitButton = (e) => {
e.preventDefault();
this.setState(prevState => ({
games: [...prevState.games, {
title: this.refs.title.value,
rating: this.refs.rating.value,
price: this.refs.price.value
}]
}));
}
render () {
return (
<div>
<form onSubmit={this.handleSubmitButton}>
<label>
Game Name
<input type="text" id="name-input" ref="title"/>
</label>
<label>
Rating
<input type="text" id="ratings-input" ref="rating"/>
</label>
<label>
Price
<input type="text" id="price-input" ref="price"/>
</label>
<button type="submit" id="submit-button">Submit</button>
</form>
<label>
Search
<input type="text" id="search-input"/>
</label>
<table id="directory-table">
<tr>
<th>Name</th>
<th>Ratings</th>
<th>Duration</th>
</tr>
{this.state.games.map(game => {
return (
<tr>
<th>{game.title}</th>
<th>{game.rating}</th>
<th>{game.price}</th>
</tr>
)
})}
</table>
</div>
);
} }