Learn ReactJS Form Example
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name:"",
email:"",
}
this.updateState = this.updateState.bind(this);
};
updateState(e) {
let name = e.target.name
let val = e.target.value
this.setState({
[name]: val
});
}
render() {
return (
<div>
<div>
<label>Name: </label>
<input type = "text" name="name" value = {this.state.name} onChange = {this.updateState} />
</div>
<div>
<label>Email: </label>
<input type = "text" name="email" value = {this.state.email} onChange = {this.updateState} />
</div>
<hr/>
<table>
<tbody>
<tr>
<td>Name:</td>
<td>{this.state.name}</td>
</tr>
<tr>
<td>Email</td>
<td>{this.state.email}</td>
</tr>
</tbody>
</table>
</div>
);
}
}
export default App;
This is a basic example of a ReactJS form. We are using the main App class and implementation from our getting started tutorial.
Notice howe we initialize this.state within our constructor function.
You'll notice that the render() method returns our HTML form. Notice how there are two input fields representing each attribute in our state object. We set the values of these inputs to state properties. This ensures the view will always be in sync with the underlying data model.
We've also added onChange event handlers to both inputs. Notice how these change events are set to the this.updateState() function. We can reference the updateState(e) function like this because we've bound this to the function via this.updateState = this.updateState.bind(this). This is important because it allows us to pass down functions to child components.
The <table> is there to dynamically present the user's inputs. Notice that when you start typing in one of the input fields, the page dynamically updates with the input's current value. This works because our updateState() function updates the state based on the event target e.target.name and e.target.value.
ReactJS Form Validation
You can validate the inputs before you update state. For example:
updateState(e) {
let name = e.target.name
let val = e.target.value
if(val.length < 6){
this.setState({
[name]: val
});
}
}
Notice how we can update our existing updateState() function to validate the inputs. In this case, we simply validate the input's length by only calling this.setState() if the input value is less than 6 characters.
Conclusion
This is a basic example of a ReactJS form. Remember that input values should be set to state properties to ensure one way data binding. This keeps views in sync with underlying data models. You can easily validate form inputs before updating the component's state object.