// sample datas structure
/* const datas = [
{
id: 1,
name: 'john',
gender: 'm'
}
{
id: 2,
name: 'mary',
gender: 'f'
}
] */ // make sure to set the default value in the useState call (I already fixed it)
const [datas, setDatas] = useState([
{
id: 1,
name: 'john',
gender: 'm'
}
{
id: 2,
name: 'mary',
gender: 'f'
}
]);
const updateFieldChanged = index => e => {
console.log('index: ' + index);
console.log('property name: '+ e.target.name);
let newArr = [...datas]; // copying the old datas array
newArr[index] = e.target.value; // replace e.target.value with whatever you want to change it to
setDatas(newArr); // ??
}
return (
<React.Fragment>
{ datas.map( (data, index) => {
<li key={data.name}>
<input type="text" name="name" value={data.name} onChange={updateFieldChanged(index)} />
</li>
})
}
</React.Fragment>
)
this.setState({items: this.state.items.map(x => x.id === someId ? {...x, attr:'val'} : x)});
<body>
<div id="root"></div>
<script>
const { useState } = React;
const App = () => {
const [myArray, updateMyArray] = useState([]);
const onClick = () => {
updateMyArray( arr => [...arr, `${arr.length}`]);
};
return [
<input type="button" onClick={ onClick } value="Update" />,
<div>{myArray.map( e =>
<div>{ e }</div>
)}
</div>
];
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
</body>
const [state, setState] = useState({ fName: "", lName: "" });
const handleChange = e => {
const { name, value } = e.target;
setState(prevState => ({
...prevState,
[name]: value
}));
};
<input
value={state.fName}
type="text"
onChange={handleChange}
name="fName"
/>
<input
value={state.lName}
type="text"
onChange={handleChange}
name="lName"
/>
React fin and update state value
React find and update state value
new item
update an object within an array