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.
This tutorial explains how to write a react toggle button component with on or off for example.
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.
Let’s create a react class component and explain with the below notes
React.component
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')
);
🧮 Tags
Recent posts
How to Convert String to Int in swift with example How to Split a String by separator into An array ub swift with example How to disable unused code warnings in Rust example Golang Tutorials - Beginner guide Slice Examples Golang Array tutorials with examplesRelated posts