5 April 2020

Toggle example in react js

  • Create Components folder under src folder
  • Add ToggleEXP.js file and add below Code
import React from "react";

class ToggleEXP extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
}

handleClick = () => {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
};

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

export default ToggleEXP;
  • Open App.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";
import ToggleEXP from "./components/ToggleEXP";

function App() {
return (
<div className="App">
<ToggleEXP />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output



No comments:

Post a Comment