Hello I am trying to change the value of isChecked
in state when checkbox is checked.
Here's my state:
const [talles, setTalles] = useState([
{ name: 'S', isChecked: false },
{ name: 'M', isChecked: false },
{ name: 'L', isChecked: false },
{ name: 'XL', isChecked: false },
])
For each element in this state an <input type="checkbox" />
is created.
The thing is I want to dinamically change the isChecked property.
Normally I would do:
setProduct({
...product,
[e.target.name]: e.target.checked
})
But that would only work if my state was like useState({ producCheckbox: '' })
I would appreaciate your help. Thanks in advance!
You can map the previous state and change the value of the changing talle:
setTalles(previousState => previousState.map(talle => {
if (talle.name === e.target.name) return ({
...talle,
isChecked: e.target.checked,
})
return talle
}))
Or same but shorter:
setTalles(previousState => previousState.map(talle =>
talle.name === e.target.name ?
({
...talle,
isChecked: e.target.checked,
})
:
talle
}))
You can find the target object by using find
method on your state, and then update the isChecked
property, like this:
function Checkbox({name, isChecked, onChange}){ return ( <React.Fragment> <label>{name}</label> <input type="checkbox" name={name} checked={isChecked} onChange={onChange}/> </React.Fragment> ); } function App(){ const [talles, setTalles] = React.useState([ { name: 'S', isChecked: false }, { name: 'M', isChecked: false }, { name: 'L', isChecked: false }, { name: 'XL', isChecked: false }, ]) // Here is the state update const handleChange = ({target: {name,checked} })=> { setTalles(talles => talles.map(t => t.name == name? ({...t, isChecked: checked}): t)) } return (<div> { talles.map(talle => <Checkbox {...talle} onChange={handleChange}/>) } <button onClick={()=> console.log(talles)}>submit</button> </div>); } ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="root"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.