0

How to change boolean property of every object using React useState hook?

const [showCard, setShowCard] = useState([
    { id: 1, show: true }, 
    { id: 2, show: true }
]);

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.