Add/remove Form Inputs Dynamically
I have a form with one initial empty input field that I want to clone using a Add button and to remove with a Remove one. As it's not recommended to use index for the keys with dyn
Solution 1:
You may simply extend your existing items
to have unique id
property - at its very simplest, you may assign the value of maximum used id
increased by 1 to that property - I guess, it'll do the trick for most of practical use cases:
const [inputs, setInputs] = useState([{id:0,value:''}]),
onRowAdd = () => {
const maxId = Math.max(...inputs.map(({id}) => id))
setInputs([...inputs, {id:maxId+1, value:''}])
}
With that, you'll have unique id
to anchor to as you delete rows:
onRowRemove = idToDelete =>setInputs(inputs.filter(({id}) => id != idToDelete))
Following is the demo of this concept:
const { useState } = React,
{ render } = ReactDOM
constForm = () => {
const [inputs, setInputs] = useState([{id:0,value:''}]),
onInput = (id,value) => {
const inputsCopy = [...inputs],
itemToModify = inputsCopy.find(item => item.id == id)
itemToModify.value = value
setInputs(inputsCopy)
},
onRowAdd = () => {
const maxId = Math.max(...inputs.map(({id}) => id))
setInputs([...inputs, {id:maxId+1, value:''}])
},
onRowRemove = idToDelete =>setInputs(inputs.filter(({id}) => id != idToDelete)),
onFormSubmit = e => (e.preventDefault(), console.log(inputs))
return (
<formonSubmit={onFormSubmit} >
{
inputs.map(({id,value}) => (
<divkey={id}><inputonKeyUp={({target:{value}}) => onInput(id,value)}
/>
<inputtype="button"onClick={onRowAdd}value="Add" /><inputtype="button"onClick={() => onRowRemove(id)} value="Remove" />
</div>
))
}
<inputtype="submit"value="Log Form Data" /></form>
)
}
render (
<Form />,
document.getElementById('root')
)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><divid="root"></div>
Solution 2:
You should create a variable that starts from 0 and adds 1 every time you add a button. That way you will keep track of everyone. Here's an example
let i = 0constadd () => {
//your function to add
i++
//remember i will be the id now
}
Post a Comment for "Add/remove Form Inputs Dynamically"