0

How to store value in a object of array using useState hook

For eg :- [ { id:1, name : "user" } ] I need to change the value of "name" using onChange function. How do i achieve this?

21st Dec 2022, 12:42 PM
karthik sudhakar
2 Answers
+ 2
Nice question, Here is the function to change value of name key const [data, setData] = useState([{name:"user", id:"1"}] function changeHandler() { setData(old => old.map(item => { if(item.name=="user") return {...item, name: 'newVlaue' return item } ) ) This function call when change event occur
22nd Dec 2022, 1:16 PM
ƬIMΛ
ƬIMΛ - avatar
0
// jsx <input type="text" onChange={changeHandler} /> // state const [items, setItems] = useState([ { id: 1, name: "user" } ]); // event function function changeHandler(event) { const newItems = items.map(item => { if (item.id === 1) { return { ...item, name: event.target.value }; } return item; }); setItems(newItems); } // To list the item names in an unordered list (ul) const itemsList = items.map(item => <li key={item.id}>{item.name}</li>); // in jsx return ( <ul> {itemsList} </ul> );
26th Dec 2022, 7:54 AM
CalviŐ˛
CalviŐ˛ - avatar