Forms are an important part of most web applications. They allow users to input data and interact with the application. In this article, we’ll take a look at how to work with forms in React.js.
Creating React Application:
To get started, we’ll need to create a new React.js project. We can do this by running the following command:
Step 1: Create a React application using the following command.
npx create-react-app gfg
Step 2: After creating your project folder(i.e. gfg), move to it by using the following command.
cd gfg
Step to run the application: Start the application using the following command:
npm run start
Project Structure: Below is the structure of the project:
Example 1: Form using the Input field
The first thing we need to do is create a form. We can do this by using the <form> tag. Inside of the <form> tag, we can add any number of input fields. Input Fields are the basic elements of a form. They allow the user to input data. We can add an Input field in React using the <input> tag but to change its value we have to use the useState hook.
App.js
import React, { useState } from 'react' ; export default function App() { const [value, setValue] = useState( "" ); return ( <div> <h2>neveropen - ReactJs Form</h2> <form> <label> Input Field:- <input value={value} onChange={(e)=>{ setValue(e.value) }}/> </label> </form> </div> ); } |
Output:
Example 2: Form Using TextArea field
A TextArea is a larger text input field. It allows the user to enter multiple lines of text. We can add a TextArea in React using the <textarea> tag but to change its value we have to use the useState hook.
App.js
import React, { useState } from 'react' ; export default function App() { const [value, setValue] = useState( "" ); return ( <div> <h2>neveropen - ReactJs Form</h2> <form> <label> Input Field:- <textarea value={value} onChange={(e)=>{ setValue(e.value) }}/> </label> </form> </div> ); } |
Output:
Example 3: Form Using Select field
A Select is a field that allows the user to select one option from a list. We can add a Select Field in React using the <select> tag.
App.js
import React, { useState } from 'react' ; export default function App() { const [value, setValue] = useState( "" ); return ( <div> <h2>neveropen - ReactJs Form</h2> <form> <label> Select Field:- <select value={value} onChange={(e)=>{ setValue(e.value) }}> <option value= "gfg1" >GfG1</option> <option value= "gfg2" >GfG2</option> <option value= "gfg3" >GfG3</option> <option value= "gfg4" >GfG4</option> </select> </label> </form> </div> ); } |
Output:
Similarly, you can add different types of form fields to your react component with the help of the useState hook.