React Button toggle on off example


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

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

React toggle Button class component example

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

  • Create a react component by extending React.component
  • Added button component in Render with jsx syntax
  • Added button click event
  • In constructor of a component,
    • Initializes the parent props by writing super(props) as a first line
    • Initialize a state by updating isOff defaults with 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 functional component with react hooks.

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

here we used inline click event handler to handle the button clicks Following is an React button 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')
);
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.