How To Handle Multiple Input Field In React Form With A Single Function?
Last Updated :
01 Oct, 2024
When building a form in React, especially one with multiple input fields, it’s essential to maintain clean, readable code. A common approach is using a single function to handle all input fields, reducing redundancy and enhancing efficiency. This article will explore how to handle multiple input fields in a React form with a single function and why this approach is optimal.
Why Use a Single Function to Handle Multiple Input Fields?
In a typical React form, each input field might have its own onChange handler. However, managing multiple fields this way becomes tedious as the form grows. By using a single function, we can handle multiple inputs efficiently, ensuring that our code remains concise and easy to maintain. Here’s how to handle multiple input fields in a React form with a single function.
Steps To Handle Multiple Input Field With A Single Function
Step 1: Create a react application using the following command.
npx create-react-app react-gfg
cd react-gfg
Folder Structure
Folder Structure
Dependencies
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example 1: This example shows how to handle multiple form input fields with a single handleChange function.
JavaScript
//App.js
import React from 'react';
import Form from './Form';
const App = () => {
return (
<div>
<Form />
</div>
);
};
export default App;
JavaScript
//Form.js
import React, { useState } from 'react';
const Form = () => {
// Initialize state using useState hook
const [formData, setFormData] = useState({
email: '',
name: '',
age: '',
address: '',
phoneNo: ''
});
// Handle form input changes
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({
...formData,
[name]: value
});
};
// Handle form submission
const handleSubmit = (event) => {
event.preventDefault();
const { email, name, age, address, phoneNo } = formData;
alert(`
____Your Details____\n
Email: ${email}
Name: ${name}
Age: ${age}
Address: ${address}
Phone No: ${phoneNo}
`);
};
// Render the form
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">Email</label>
<input
name="email"
placeholder="Email"
value={formData.email}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="name">Name</label>
<input
name="name"
placeholder="Name"
value={formData.name}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="age">Age</label>
<input
name="age"
placeholder="Age"
value={formData.age}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="address">Address</label>
<input
name="address"
placeholder="Address"
value={formData.address}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="phoneNo">Phone Number</label>
<input
name="phoneNo"
placeholder="Phone No"
value={formData.phoneNo}
onChange={handleChange}
/>
</div>
<div>
<button>Create Account</button>
</div>
</form>
);
};
export default Form;
To start the application run the following command.
npm start
Output
Handle Multiple Input Field In React Form With A Single Function
Example 2: In this example we will create a box by taking input from different form fields.
JavaScript
//App.js
import React from 'react';
import BoxList from './BoxList'
const App = () => {
return (
<BoxList />
);
};
export default App;
JavaScript
//Box.js
import React, { Component } from "react";
class Box extends Component {
render() {
const { height, width, bc } = this.props.attrs;
const style = {
width: `${width}em`,
height: `${height}em`,
backgroundColor: bc,
};
return <div style={style} />;
}
}
export default Box;
JavaScript
//NewBoxForm.js
import React, { Component } from 'react'
class NewBoxForm extends Component {
constructor(props) {
super(props)
this.state = { height: 0, width: 0, bc: '' }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(event) {
event.preventDefault()
this.props.create(this.state)
this.setState({ height: 0, width: 0, bc: '' })
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label htmlFor='height'>Height</label>
<input
name='height'
placeholder='Height'
value={this.state.height}
onChange={this.handleChange}
/>
</div>
<div>
<label htmlFor='width'>Width</label>
<input
name='width'
placeholder='Width'
value={this.state.width}
onChange={this.handleChange}
/>
</div>
<div>
<label htmlFor='bc'>Background Color</label>
<input
name='bc'
placeholder='Background Color'
value={this.state.bc}
onChange={this.handleChange}
/>
</div>
<div>
<button>Add a new Box!</button>
</div>
</form>
)
}
}
export default NewBoxForm
JavaScript
//BoxList.js
import React, { Component } from 'react'
import { v4 as uuid } from 'uuid'
import NewBoxForm from './NewBoxForm'
import Box from './Box'
class BoxList extends Component {
constructor(props) {
super(props)
this.state = { boxes: [] }
this.createBox = this.createBox.bind(this)
}
createBox(attrs) {
const newBox = { ...attrs, id: uuid() }
this.setState({
boxes: [...this.state.boxes, newBox]
})
}
renderBoxes() {
return this.state.boxes.map(box => (
<Box key={box.id} attrs={box} />
))
}
render() {
return (
<div>
<h1>Make New Color Boxes!</h1>
<NewBoxForm create={this.createBox} />
{this.renderBoxes()}
</div>
)
}
}
export default BoxList
Output:
Handle Multiple Input Field In React Form With A Single Function