React JS Tutorial - Forms
In this tutorial, we will learn about forms in React. Let's see how to add a form to our application.
Switch to your project and open the Post Component. Inside the Post Component, add a form tag and include some input fields as follows:
<form>
<input type="text" name="name" />
<input type="email" name="email" />
<input type="text" name="phone" />
<button>Submit</button>
</form>
Next, we need to create a function to handle changes to the form fields. Create a handleChange function as follows:
handleChange=(e)=>{
this.setState({
[e.target.name]:e.target.value.
});
}
Now, add the onChange event to the input fields and call the handleChange function as follows:
<form>
<input type="text" name="name" onChange={this.handleChange} />
<input type="email" name="email" onChange={this.handleChange} />
<input type="text" name="phone" onChange={this.handleChange} />
<button>Submit</button>
</form>
Next, we need to create a function to handle the form submission. Create a handleSubmit function as follows:
handleSubmit=(e)=>{
e.preventDefault();
console.log('Name',this.state.name);
console.log('Email',this.state.email);
console.log('Phone',this.state.phone);
}
Now, add the onSubmit event to the form and call the handleSubmit function as follows:
<form onSubmit={this.handleSubmit} >
<input type="text" name="name" onChange={this.handleChange} />
<input type="email" name="email" onChange={this.handleChange} />
<input type="text" name="phone" onChange={this.handleChange} />
<button>Submit</button>
</form>
Let's test the form. Go to your browser and make the console visible by pressing Ctrl + Shift + i. Then, click on the Console tab.
Fill out the form by entering your name, email, and phone number, and then click the submit button. After submitting the form, you should see the name, email, and phone number displayed in the console.
This demonstrates how to use forms in React. By following these steps, you can create and handle forms in your React application.