Pages

How to create a toggle button in React.js?

Here, we are using the If/else statement to toggle the react element. The if statement executes a certain condition, if the statement is true and executes the else condition if the statement is false.


Let’s see how to use if/else in toggle reactjs.

First, we will import the useState hook.


import React, {useState} from 'react';


Now, we need to define useState, create a getter and setter variable, and set the default value to “true”. We can also use “false” but to show the element initially, we set the value to “true”.


const[toggle,setToggle]= React.useState(true);


Take any text in the header and set the toggle in an if/else condition. If the condition is true then show the text; otherwise, hide the text.


Now, we will create one button. In this button, take an onClick function. Within this function, call the setToggle setter and pass the (!toggle) to return an opposite value when clicked.

button onClick={() => setToggle(!toggle)}>Toggle Button</button>


Here, we can see the full code.


import logo from './logo.svg';

import './App.css';

import React, {useState} from 'react';


function App() {

  const[toggle,setToggle]= React.useState(true);

  return (

    <div className="App">

      {

    toggle? <h1>Toggle tutorial</h1> :null

      }

    <button onClick={() => setToggle(!toggle)}>Toggle Button</button>

    </div>

  );

}


export default App;



The output is:


The default value before adding the toggle button in react js was:


On clicking on “Toggle button”, the text gets hidden.


Again on clicking on “Toggle Button”, the text will be shown.




No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...