{

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.

React toggle Button 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.

useState hook is used to initialize with initial value and function which changes 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')
);
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.





Related posts

ReactJS Append variables with strings, jsx state and prop concatenate html

How to display the content of a JSON file in React with example

Reactjs Fix Must call a super constructor in derived class before accessing this

How to change default port in React with create-react-app command?

How to create an react typescript application | Create-react-app typescript application

How to handle broken images in React | fallback for broken images

Fixing an error You are running create-react-app 4.0.3, which is behind the latest release (5.0.0) in React