Reputation:
I am following the ReactJS tutorial on the official site and I am curious about a design choice. Basically the tutorial said we need to have a handleChange function on every input's onChange.
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
Does it mean if I have a form that has 10 text inputs and 3 checkbox inputs every single one of them needs to have a "handleChange" function?
What is the best practices of handling this situation?
Upvotes: 2
Views: 2521
Reputation: 19133
It is a recommended way to use controlled components
, which is handling all the inputs
with an onChange()
handler. But, you don't need to handle the in a different handler for each, you can handle all the onChange()
with on handler but, identify the target uniquely and set the value to the state.
See the fiddle for an example https://jsfiddle.net/Pranesh456/ga2csaty/4/
In this example, I've used a common
onChange()
handler but I uniquely identified each input box with theirid
and populated the state based on theid
which is been served as thevalue
for the input boxes.
For more reference check React's controlled components
Upvotes: 2
Reputation: 1309
Not really, you can just remove value={this.state.author}
and onChange={this.handleAuthorChange}
from the code and it will still work. If you want to refer your input when you are submitting a form, I'd use ref
feature in React. It is a way to create a reference to the input for later use.
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
<input
type="text"
placeholder="Your name"
ref={(c) => this.yourNameField = c}
/>
Upvotes: 0