Reputation: 421
How would you guys do a form submission? I have no problem making a form but I saw 2 different approach. Personally I use state to bind the form value
<input onChange={this.handleInputChange} value={this.state.username} type="text" name="username" />
to get the input value I will do this
handleInputChange = () => (
const username = e.target.username.value;
)
It worked but not sure this is a good approach, another approach is using refs.
The good thing is no need to put onChange on every fields, in onSubmit simply do this
this.refs.username.value
and you have ur element like this <input ref="username" type="text" />
But how to set the value of the username if the initial load is an ajax?
Upvotes: 1
Views: 935
Reputation: 109
I recommend to not use refs unless you have no other way of doing things. https://facebook.github.io/react/docs/refs-and-the-dom.html
Your approach with binding the value to state seems like the way to go.
Upvotes: 2
Reputation: 7734
The good thing about using the onChange(one-way binding) is that you have full control over the input data.
Say if you want input to have only alphabets
handleInputChange = () => (
// you can have validation code here to check if the
// input has only alphabets and return if otherwise
const username = e.target.username.value;
)
Upvotes: 0