Noble Polygon
Noble Polygon

Reputation: 806

Combining multiple React States into one variable

I'm working on a project in React where I can hide/show multiple elements on screen with the useState hook.

example

  const [nameLabel, setNameLabel] = useState(true);
  const [numberLabel, numberLabel] = useState(true);
  const [departure, setDeparture] = useState(true);
  const [arrival, setArrival] = useState(true);

I have about 20 of these booleans, but now I want to create a single variable so I can show or hide all these booleans at once.

Is it possible to combine all of these in into one variable that I can call to show or hide all the elements at once?

Upvotes: 0

Views: 1584

Answers (2)

Brian Thompson
Brian Thompson

Reputation: 14355

If I understand your question correctly, I think you're better off using a function to toggle them all at once (the extra all state is optional. You can use whatever logic you want, I just used it to help illustrate).

This allows you to keep things independent like you had it before, but with a helper function to update all of them at once.

const {useState} = React;

const Example = () => {
  const [all, toggle] = useState(false);
  
  const [nameLabel, setNameLabel] = useState(true);
  const [numberLabel, setNumberLabel] = useState(true);
  const [departure, setDeparture] = useState(true);
  const [arrival, setArrival] = useState(true);
  
  const toggleAll = (bool) => {
    setNameLabel(bool);
    setNumberLabel(bool);
    setDeparture(bool);
    setArrival(bool);
    
    toggle(!bool);
  }
   
  return (
    <div>
      <div>
        <button onClick={() => toggleAll(all)}>Toggle All</button>
      </div>
      <div>
        <button onClick={() => setNameLabel(!nameLabel)}>Name: {nameLabel.toString()}</button>
      </div>
      <div>
        <button onClick={() => setNumberLabel(!numberLabel)}>Number: {numberLabel.toString()}</button>
      </div>
      <div>
        <button onClick={() => setDeparture(!departure)}>Departure: {departure.toString()}</button>
      </div>
      <div>
        <button onClick={() => setArrival(!arrival)}>Arrival: {arrival.toString()}</button>
      </div>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

chandan_kr_jha
chandan_kr_jha

Reputation: 557

You can create an object with your booleans and update a single key. Something like

const [data, setData] = useState({
  nameLabel: true,
  numberLabel: true,
  departure: true,
  arrival: true
});

Call setData

setData({ ...data, nameLabel: false })

Refer this link codesandbox

Upvotes: 4

Related Questions