How to Toggle State Value in React

Irakli Tchigladze Feb 02, 2024
How to Toggle State Value in React

Since the early days of the internet, front-end developers have used JavaScript to add dynamic and interactive features to their web pages. These days, the process of building web applications is vastly different than it was 20 years ago.

Developers still need to build web apps with dynamic, interactive features. They tend to use JavaScript-based frameworks.

React is especially popular for building modern user interfaces. It maintains an internal state, which allows you to add dynamic features to your apps.

This article will show you how to toggle the state variable in React.

Toggle State Value in React

In React, every component has a state. Developers often use the state to capture input from users.

For example, nowadays, it is common to give users the option to use the website’s light mode or dark mode versions.

To implement this feature in React, we would have to set a state variable nightMode (or any other descriptive variable name) to either true or false. Then, we could use conditional styling to change the background and text colors depending on the current value of this variable.

Let’s take a look at an example:

export default function App() {
  let [nightMode, setNightMode] = useState(false);
  const applyNightMode = {
    backgroundColor: nightMode ? "black" : "white",
    color: nightMode ? "white" : "black",
    height: "300px"
  };
  return (
    <div className="App" style={applyNightMode}>
      <h1>Hello to our web app</h1>
      <button onClick={() => setNightMode(!nightMode)}>
        Toggle state variable
      </button>
    </div>
  );
}

In this case, we have a nightMode variable set to false by default. However, we want to give users a choice to use the dark mode, and if users don’t like dark mode, we want to provide them with the option to go back to normal.

For that, we need to use React toggle state. Go to the live CodeSandbox demo to try the example code in action.

Capture Changes in the Input Elements

In the example above, we have the simplest example: clicking a button toggles the current value of the nightMode state variable. Alternatively, you can use the checkbox or another element to toggle the state variable in React.

Depending on your HTML element, you need to fire your event handler for the right event. For buttons, we use the onClick attribute to make changes in response to users’ clicks.

If you use the checkbox, you might want to use the onChange attribute instead.

Update the State for Class Components

In the example above, we used the useState() hook to update the state variable in React. This hook is available only if you run a React version 16.8 or newer version.

Some developers prefer to write class components, even if hooks are available.

React developers are prohibited from directly mutating the state object. We need to use the setState() method to update the state in class components.

The argument needs to be the entire state object, even if you only want to toggle the value of a specific property. Change the value of a particular property but still pass the entire object.

Let’s take a look at an example:

class App extends React.Component {
  constructor() {
  super();
  this.state = {nightMode: false};
  }
  render() {
    const applyNightMode = {
    backgroundColor: nightMode ? "black" : "white",
    color: nightMode ? "white" : "black",
    height: "300px"
  };
    return (
    <div className="App" style={applyNightMode}>
      <h1>Hello to our web app</h1>
      <button onClick={() => setState({nightMode: !this.state.nightMode})}>
        Toggle state variable
      </button>
    </div>
  );
  }
}

Initializing the state in class components takes more lines of code than functional component hooks. As you can see, we used the constructor() to create the initial state object.

We used the setState() method within JSX to update the value of the nightMode property. We passed the new state object as a first argument to the setState() method.

To toggle state in React, we set the new value of the nightMode property to the opposite of the current value.

Update the State for Functional Components

Let’s take a look at the example code again:

export default function App() {
  let [nightMode, setNightMode] = useState(false);
  const applyNightMode = {
    backgroundColor: nightMode ? "black" : "white",
    color: nightMode ? "white" : "black",
    height: "300px"
  };
  return (
    <div className="App" style={applyNightMode}>
      <h1>Hello to our web app</h1>
      <button onClick={() => setNightMode(!nightMode)}>
        Toggle state variable
      </button>
    </div>
  );
}

The useState() hook returns two values: the state value (which we stored in the nightMode variable ) and the function to update this specific variable (which is stored in the setNightMode variable).

It is a convention to name your variables this way - a descriptive name for the state variable and then set+variableName for the function that updates it.

The handler function for the click event is simple. We used the opposite operator ! and ran the setNightMode() function to set the state variable value to the opposite of what it is now.

Irakli Tchigladze avatar Irakli Tchigladze avatar

Irakli is a writer who loves computers and helping people solve their technical problems. He lives in Georgia and enjoys spending time with animals.

LinkedIn

Related Article - React State