this is the object . How can i input value through form tag in listItem key dynamically in react
{
name: "",
dueDate: "",
grossAmount: "",
billNo: "",
billDate: "" ,
listItem:[{ productName: "", quantity: null, price: null, amount: null, gstRate: null}],
gstAmount: null,
netAmount: null,
notes: "",
status: " "
}
CodePudding user response:
Assuming object is stored in a state using useState hook
const [obj,setObj] = useState({
name: "",
dueDate: "",
grossAmount: "",
billNo: "",
billDate: "" ,
listItem:[{ productName: "", quantity: null, price: null, amount: null, gstRate: null}],
gstAmount: null,
netAmount: null,
notes: "",
status: " "
})
You can do..
state for input:
const [productName,setProductName] = useState("");
And for input you can do something like this. Note: I just did this for changing productName, but you can do this for any of the other keys of the obj.
<form>
<input type="text" onChange={(e)=>setProductName(e.target.value)} />
<button onClick={()=>setObj({...obj,lastItem:[...lastItem[0],productName]})}></button>
</form>
CodePudding user response:
First add name
attribute to your input element. Then create a onChangeHandler function. This function can handle all changes for every inputs you have.
Your inputs (the name attribute should be the same as your object key):
<input name='dueDate' onChange={onChangeHandler} type="text" value={myObject.dueDate} />
onChangeHandler function:
const onChangeHandler = (event) => {
myObject = {
return {...myObject, [event.targer.name]: event.targer.value}
}
}