I have a react form with two inputs:
<input type="name" className="form-control" placeholder="Name"/>
<input type="description" className="form-control" placeholder="Description"/>
Because the types of the input fields are name and description respectively,
I assumed that on form submission the fields this.state.name and this.state.description will be updated.
However, when I submit the form, these fields do not change their values.
The full code for the form is:
<form>
<div className="form-group">
<label>Name</label>
<input type="name" className="form-control" placeholder="Name"/>
</div>
<div className="form-group">
<label>Description</label>
<input type="description" className="form-control" placeholder="Description"/>
</div>
<button type="submit" onClick={this.handleSubmit} className="btn btn-default">Submit</button>
</form>
How can I get the values filled in by the user?
There are several ways how you can get values from form, one of them you can use refs like this
<input ref="name" type="name" className="form-control" placeholder="Name"/>
<input ref="description" type="description" className="form-control" placeholder="Description"/>
var name = ReactDOM.findDOMNode(this.refs.name).value,
description = ReactDOM.findDOMNode(this.refs.description).value;
Example
Note Example for React version >= 0.14 where there is react-dom. For version <= 0.13 instead of ReactDOM use React
Also you can use states like this
<input onChange={this.updateName} type="name" className="form-control" placeholder="Name"/>
<input onChange={this.updateDescription} type="description" className="form-control" placeholder="Description"/>
handleSubmit: function (e) {
e.preventDefault();
var name = this.state.name;
description = this.state.description;
},
getInitialState: function () {
return { name: '', description: '' };
},
updateName: function (e) {
this.setState({ name: e.target.value });
},
updateDescription: function (e) {
this.setState({ description: e.target.value });
}
Example
You should do as the original documentation says here https://facebook.github.io/react/docs/forms.html#controlled-components
I have modified the code sample in the docs to suit your case. I know this could be done more dynamic but I have done it like this for the sake of simplicity.
getInitialState: function() {
return {
valueName: 'Name',
valueDesc: 'Description'
};
},
// here you handle all the changes in the input
handleNameChange: function(event) {
this.setState({valueName: event.target.value});
},
handleDescChange: function(event) {
this.setState({valueDesc: event.target.value});
},
render: function() {
return (<div>
<input type="name" value={this.state.valueName} onChange={this.handleChange} />
<input type="description" value={this.state.valueDesc} onChange={this.handleChange} />
</div>);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With