How to change boolean property of every object using React useState hook?
const [showCard, setShowCard] = useState([
{ id: 1, show: true },
{ id: 2, show: true }
]);
You can pass a function to setShowCard – see the Functional updates section in the documentation of useState. The first argument is the previous state, which you can map over to e.g. toggle the show property of every item:
setShowCard(prevState => prevState.map(item => ({
...item,
show: !item.show,
})));
Runnable example:
const { useState } = React;
function App() {
const [showCard, setShowCard] = useState([
{ id: 1, show: true },
{ id: 2, show: true },
]);
function toggle() {
setShowCard(prevState => prevState.map(item => ({
...item,
show: !item.show,
})))
}
return (
<div>
<pre>{JSON.stringify(showCard, null, 2)}</pre>
<button onClick={toggle}>Toggle</button>
</div>
);
}
ReactDOM.render(<App />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>