{

React Button toggle on off example


This tutorial explains how to write a react toggle button component with on or off for example. Learn React JSX  Tutorials with examples

In this component, First displays the button with On text, On clicking this button, how to change the text from on or off or vice verse.

Button clicking state that contains on(true) and off(false) is maintained in React State object. You can set the default to true or false.

The current state is the default state. It can be changed using a button click event from a user.

React Button toggle on off class component example

Let’s create a react class component and explain with the below notes

  • Create a react component by extending React. component
  • Added button component in Render with JSX syntax
  • Added button click event
  • In the constructor of a component,
    • Initializes the parent props by writing super(props) as a first-line
    • Initialize a state by updating isOff defaults with a Boolean value to false
  • Added button handler for using click binding

Here is an example

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

class ToggleButtonOnOff extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {isOff: false};
  }

  handleClick() {
    this.setState({isOff:!this.state.isOff});
  }

  render() {
    const { isOff } = this.state;
    let title=this.state.isOff? "ON":"OFF";
    return (
      <button onClick={this.handleClick}>{title}</button>
    );
  }
}

ReactDOM.render(
  <ToggleButtonOnOff />,
  document.getElementById('root')
);

The above code is rewritten using a functional component with react hooks.

React Button toggle on off Functional component example

Functional components are normal javascript functions that return JSX element and displayed to DOM element.

useState hook is used to initialize with initial value and function which changes its value on click event handler.

here we used an inline click event handler to handle the button clicks Following is a React button to toggle on-off function component example

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

const ToggleButtonOnOff = () => {
  const [isOff, setIsOff] = useState(true);

  return (
    <button onClick={() => setIsOff(!isOff)}>{ isOff ? 'ON' : 'OFF' }</button>
  );
}

ReactDOM.render(
  <ToggleButtonOnOff />,
  document.getElementById('root')
);

Conclusion

You can write the component using ES6 Class components or Functional components that uses useState hook used to maintain state

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.