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?
2 odpowiedzi
+ 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
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>
);