How to toggle elements in React Js?

In this tutorial, we will see how to toggle elements in React js. Toggling simply means to show and hide the element alternatively with each click of the button. The same concept is required in many applications like showing and hiding notifications.

Toggle elements in React Js

We will create a button named Toggle. We won’t create another component for this tutorial. It will just print a demo sentence on each toggle. You can create another component and pass it instead of the sentence. We will use the useState hook. You can go through What is useState() hook in ReactJs? for better understanding.

First, let us create a button and a state variable called show. The code will look like this:

import React,{useState} from 'react'

const App = () => {
  const[show,setShow]=useState(true);
  return (
    <div>
      <button>Toggle</button>
    </div>
  )
}

export default App

The output would look like this:Toggle elements in React jS

Nothing will happen if we click on the toggle button. So now we need to render content dynamically. If our show variable is true then only we should show the element. To render contents dynamically in react, we need to write javascript code. The code should be within curly brackets as React needs to understand that this is a javascript code.  We will use a conditional operator for this.

The syntax of the conditional operator is:

(condition)?statement1:statement2

If the condition is true then statement1 is executed else statement2 is executed. So we will check if the show is true or not. If true then we will display the element. We will display null if the show is false. The code will look like this:

import React,{useState} from 'react'

const App = () => {
  const[show,setShow]=useState(true);
  return (
    <div>
      {
        show?<h1>Hello, I am Muskan.</h1>:null
      }
      <button>Toggle</button>
    </div>
  )
}

export default App

The output would look like this:

const[show,setShow]=useState(true);

This is not complete yet. It does not toggle on clicking the button. So we will add onClick on our button. We will pass setShow function in that. The setShow function was returned by the useState. The code will look like this:

import React,{useState} from 'react'

const App = () => {
  const[show,setShow]=useState(true);
  return (
    <div>
      {
        show?<h1>Hello, I am Muskan.</h1>:null
      }
      <button onClick={()=>setShow(!show)}>Toggle</button>
    </div>
  )
}

export default App

Notice that we are setting the show as ‘not show’. Initially, the show is true. On clicking the button, it will become false. On clicking again, it will become true. This will go on and the value of the show will be inverted with each click.

This completes our app. The toggle works perfectly.

Conclusion

It is easy to toggle in React. You should just know the concept. Keep learning.

Leave a Reply

Your email address will not be published. Required fields are marked *