Forms are an important part of web development. Form handling is a crucial user interaction for websites. React hooks provide a concise and very efficient way to handle the state of the form as the user interacts with the form fields. There are mainly two react hooks for this purpose.
- useState:- useState hook is used to manage the current state of any input field in the context of form handling. useState is a very nice way to hold the data over the website till the time you want.
- useEffect:– useEffect is used to perform side effects on the website. use effect can be used to trigger actions after successful form submission as shown in example one. useEffect can also be used in case the form requires additional data to be fetched from the server, such as options of the `select` form field.
In this article, we will learn how to efficiently manage forms using react hooks.
Prerequisites:
Steps to Create a React App
Step 1: Create a new react application using the commands provided below.
npx create-react-app form-handling
Step 2: Navigate into the directory with the command provided below.
cd form-handling
Approach 1: Basic form Handling
Basic form handling defines a state where the form data is held as input by the user.
Example
Here is an example of form handling using react hooks. We have a username state defind using useState hook and a function handleUsernameChange to handle the change in the username. Another useState is defind to check whether the form has been submitted or not. On successful form fillup, there is a handleSubmit function to submit the form. Comments are provided in the code for each and every possible lines of code for better understanding.
// App.js import React, { useState, useEffect } from 'react' ;
import './App.css' ;
function App() {
const [username, setUsername] = useState( '' );
const [submittedUsername, setSubmittedUsername] = useState( '' );
const handleUsernameChange = (e) => {
setUsername(e.target.value);
console.log({ "username" : username })
};
const handleSubmit = (e) => {
e.preventDefault();
setSubmittedUsername(username);
};
useEffect(() => {
if (submittedUsername) {
alert(`Submitted username: ${submittedUsername}`);
}
}, [submittedUsername]);
return (
<div className= "container" >
<form onSubmit={handleSubmit} className= "form" >
<label htmlFor= "username" className= "label" >Username:</label>
<input
type= "text"
id= "username"
value={username}
onChange={handleUsernameChange}
className= "input"
placeholder= "Enter your username"
/>
<button type= "submit" className= "button" >Submit</button>
</form>
</div>
);
} export default App;
|
/*App.css*/ .container { display : flex;
justify- content : center ;
align-items: center ;
height : 100 vh;
} .form { width : 300px ;
padding : 20px ;
border-radius: 8px ;
background-color : #f0f0f0 ;
box-shadow: 0 4px 6px rgba( 0 , 0 , 0 , 0.1 );
} .label { margin-bottom : 10px ;
display : block ;
font-size : 16px ;
} .input { width : 100% ;
padding : 10px ;
font-size : 16px ;
border : 1px solid #ccc ;
border-radius: 4px ;
box-sizing: border-box;
margin-bottom : 20px ;
} .button { width : 100% ;
padding : 10px ;
background-color : #007bff ;
color : #fff ;
font-size : 16px ;
border : none ;
border-radius: 4px ;
cursor : pointer ;
transition: background-color 0.3 s;
} .button:hover { background-color : #0056b3 ;
} |
Output:
Run the following command to start the server
npm start
Approach 2: Dynamic Form Handling
In this approach, the form is dynamic where you can add form fields as well and type into it. It is helpful in case you want to submit an array of inputs.
Example: The example demonstrates a functional component defined called `Dynamic Form`, that defines the logic of displaying an array of input fields.
// App.js import React, { useState } from 'react' ;
const App = () => { const [fields, setFields] = useState([{ value: '' }]);
const handleChange = (index, event) => {
const values = [...fields];
values[index].value = event.target.value;
setFields(values);
};
const handleAddField = () => {
setFields([...fields, { value: '' }]);
};
const handleRemoveField = (index) => {
const values = [...fields];
values.splice(index, 1);
setFields(values);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log( 'Form submitted with fields:' , fields.map(field => field.value));
};
return (
<div style={{ marginTop: '60px' , fontFamily: 'Arial, sans-serif' , maxWidth: '400px' , margin: 'auto' }}>
<h2 style={{ fontSize: '24px' , marginBottom: '16px' }}>Dynamic Form Fields</h2>
<form onSubmit={handleSubmit} style={{ marginBottom: '16px' }}>
{fields.map((field, index) => (
<div key={index} style={{ marginBottom: '8px' }}>
<input
type= "text"
value={field.value}
onChange={(event) => handleChange(index, event)}
style={{ padding: '8px' , marginRight: '8px' , border: '1px solid #ccc' ,
borderRadius: '4px' , width: '200px' }}
/>
<button type= "button" onClick={() => handleRemoveField(index)} style={{ padding: '8px' ,
background: 'red' , color: '#fff' , border: 'none' , borderRadius: '4px' , cursor: 'pointer' }}>
Remove</button>
</div>
))}
<button type= "button" onClick={handleAddField} style={{ marginTop: '10px' , padding: '8px' ,
background: 'green' , color: '#fff' , border: 'none' , borderRadius: '4px' , cursor: 'pointer' ,
marginRight: '8px' }}>Add Field</button>
<button type= "submit" style={{ padding: '8px' , background: 'blue' , color: '#fff' , border: 'none' ,
borderRadius: '4px' , cursor: 'pointer' }}>Submit</button>
</form>
</div>
);
}; export default App;
|
Output:
Start the server by running the following command
npm start