React Forms
React offers a stateful approach to build a form. The component handles the React form rather than the DOM. Forms are usually implemented using the controlled components. Let's have a look on how we can add forms to React:
class FirstComponent extends React.Component {
render() {
return (
<form>
<label>Enter Name</label>
<input type="text"/>
</form>
);
}
}
In the above example, a form has been added to the component. Now let's see how we can handle forms in React.
Form Handling
In React, the forms are handled by the components, so the data is stored in the component state
. State can be updated as the data updates, using the event handlers like onChange
. Let's have a look:
import React from 'react'
class FirstComponent extends React.Component {
constructor(){
super();
this.state = {
val: ""
}
//Binding the 'this' keyword
this.changeHandler = this.changeHandler.bind(this)
}
changeHandler(e){
alert('Value : '+ e.target.value);
this.setState({
val: e.target.value
})
}
render(){
return (
<form>
<label>Enter Name</label>
<input type='text' onChange={this.changeHandler}/>
</form>
)
}
}
The state
needs to be initialized in the constructor before it can be used.
The input field value can be accessed using e.target.value
.
Dealing with Multiple Input fields
Let's have a look on how we can have multiple input fields:
class FirstComponent extends React.Component {
constructor(){
super();
this.state = {
firstInput: "",
secondInput: ""
}
//Binding the 'this' keyword
this.clickHandler = this.clickHandler.bind(this)
}
//First Input Change
firstchangeHandler(e){
this.setState({
firstInput: e.target.value
})
}
//Second Input Change
secondchangeHandler(e){
this.setState({
secondInput: e.target.value
})
}
render(){
return (
<form>
<label>Enter First Name</label>
<input type='text' onChange={this.firstchangeHandler}/>
<label>Enter Last Name</label>
<input type='text' onChange={this.secondchangeHandler}/>
</form>
)
}
}
Forms Submission
Submit action can be controlled by adding an event Handler in the onSubmit attribute. Let's have a look:
class FirstComponent extends React.Component {
constructor(){
super();
this.state = {
firstInput: "",
secondInput: ""
}
//Binding the 'this' keyword
this.clickHandler = this.clickHandler.bind(this)
}
//First Input Change
firstchangeHandler(e){
this.setState({
firstInput: e.target.value
})
}
//Second Input Change
secondchangeHandler(e){
this.setState({
secondInput: e.target.value
})
}
submitHandler(e){
e.preventDefault();
alert(`Details are: First Name: ${this.state.firstInput}, Last Name : ${this.state.secondInput}`)
}
render(){
return (
<form onSubmit={this.submitHandler}>
<label>Enter First Name</label>
<input type='text' onChange={this.firstchangeHandler}/>
<label>Enter Last Name</label>
<input type='text' onChange={this.secondchangeHandler}/>
<button type='submit'>Submit</button>
</form>
)
}
}
Using e.preventDefault()
, we can avoid the reloading of the page.