[PART 2] Add or Remove Input Fields Dynamically with React JS ✅ Input Value in Multiple Input Fields
In the first part we have added and removed inputs . In this video we have implemented handleChange method to fill values in the inputs
import { useState } from "react";
function App() {
const [hobby, setHobby] = useState([''])
const handleChange = (value, index) => {
const newHobby = hobby.map((hobbyItem, hobbyIndex) => {
return hobbyIndex === index ? value : hobbyItem
})
setHobby(newHobby)
}
return (
<div>
Hobbies :
<button
onClick={() => {
setHobby([...hobby, ''])
}}
>
ADD
</button>
{
hobby.map((item, index) => {
return <div style={{ display: 'flex' }}>
<input value={item} onChange={(e) => handleChange(e.target.value, index)} />
<button
onClick={() => {
const newarr = hobby.filter((i, j) => {
return index !== j
})
console.log(newarr)
setHobby(newarr)
}}
>
DELETE
</button>
</div>
})
}
</div>
);
}
export default App;
Check the Part1 and Part 2 for more details :
Comments
Post a Comment