How to create toggle button in react
- Install react and create new project
How To Install React JS and Setup Your React Application – BlogsHub
2. Create New component
A) Create Components folder inside src , create Togglecomponent folder inside Components and then create Togglecomponent.js inside Togglecomponent folder.
B) Import React and useState inside Togglecomponent.js
C) Create a button and call a function on click.
<button className='btn' onClick={onShowClick}> Toggle</button>
const [show, setShow] = useState(false);
const onShowClick = () => {
if (show == false){
setShow(true);
}
else {
setShow(false);
}
}
Complete Code of Togglecomponent.js
import React from "react";
import { useState } from 'react';
function Togglecomponent (){
const [show, setShow] = useState(false);
const onShowClick = () => {
if (show == false){
setShow(true);
}
else {
setShow(false);
}
}
return (
<>
<button className='btn' onClick={onShowClick}> Toggle</button>
{show && <h1 >Show</h1>}
</>
)
}
export default Togglecomponent;
D) Import  Togglecomponent.js component inside app.js
import Togglecomponent from './Components/Togglecomponent/Togglecomponent';
<Togglecomponent/>
Complete Code of App.js
import logo from './logo.svg';
import './App.css';
import Togglecomponent from './Components/Togglecomponent/Togglecomponent';
function App() {
const [showModal, setShowModel] = useState(false)
return (
<div className="App">
<Togglecomponent/>
);
}
export default App;
Run Your project using below command
NPM start
![](https://blogshub.co.in/wp-content/uploads/2024/07/image.png)
![](https://blogshub.co.in/wp-content/uploads/2024/07/image-1.png)
Happy Learning 🙂