Handling user inputs with forms is the most important part of your web application. React provides the mechanism to work with states with HTML forms.
Uncontrolled Elements
When a form element is not linked to a React state, it is called an uncontrolled element.
class SearchBar extends React.Component {
onInputChange(event) {
//console.log(event.target.value);
}
render() {
return (
<div className="ui segment">
<form className="ui form">
<div className="field">
<label>{this.props.title}</label>
<input type="text"
onChange={(this.onInputChange)} />
</div>
</form>
</div>
);
}
}
- React does not know the values of uncontrolled elements.
- You need to access HTML DOM to retrieve the values.
Controlled Elements
The power of React shines when a form element is linked to a React state.
- In the controlled element, the value is stored in the React state.
- You do not need to access HTML DOM to retrieve the values.
How the controlled element works:
- A user types in an input box.
- A callback function (event handler) gets invoked.
- The event handler updates the state with the “setState()” method.
- A component is rerendered.
- An input box got a value from the state.
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
//console.log(event.target.value);
this.setState({
term: event.target.value.toUpperCase()
})
}
render() {
return (
<div className="ui segment">
<form className="ui form">
<div className="field">
<label>{this.props.title}</label>
<input type="text"
value={this.state.term}
onChange={(this.onInputChange)} />
</div>
</form>
</div>
);
}
}
The example shows how React saves form data inside the state. Any lowercase characters are converted to uppercase letters.
- An event handler needs to be bound properly to the “this” object.
- The “state” should be initialized properly.
- The “value” attribute of an input needs to be linked to the proper state value.
Handling Form Submit
The default behavior of submitting a form is to refresh the form. To prevent the default behavior, you need to call the “event.preventDefault()”
onFormSubmit(event) {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
</form>
);
}