Let's create a simple form first. The syntax is straightforward:
import './App.css';
function App() {
return (
<div className="App">
<form>
<div>
<input
name='name'
placeholder='Name'
/>
<input
name='age'
placeholder='Age'
/>
</div>
</form>
</div>
);
}
export default App;
Here's what it'll look like:
Screenshot-2022-02-06-171620
We have two input fields, which are Name and Age. But these fields are static. So, let's made them dynamic using React States.
How to Make Forms Dynamic in React
Create one state called InputFields. It will have an object, with name and age properties.
const [inputFields, setInputFields] = useState([
{name: '', age: ''}
])
Now, let's map our form fields from their inputFields state.
import { useState } from 'react';
import './App.css';
function App() {
const [inputFields, setInputFields] = useState([
{ name: '', age: '' }
])
return (
<div className="App">
<form>
{inputFields.map((input, index) => {
return (
<div key={index}>
<input
name='name'
placeholder='Name'
/>
<input
name='age'
placeholder='Age'
/>
</div>
)
})}
</form>
</div>
);
}
export default App;
Now, we will see only one set of input fields, because we have only one object in the inputFields state. If we add more objects, we will see multiple input fields.