How to Create a Simple Toggle Button with React.js

--

React.js makes it incredibly easy to build interactive UIs.
Meeting react along the line was indeed a relief in a way, Today, I will be sharing how to create a simple toggle button—a fundamental component in any developer's toolkit.

#Step 1: Set Up Your React Environment:

If you haven't already. start by setting up a new React project. You can do this by running:

```bash

npm create vite@latest

 C:\Users\user\OneDrive\Desktop\my-react-app> npm  create vite@latest
√ Project name: ... toggle-button
√ Select a framework: » React
√ Select a variant: » JavaScript

Scaffolding project in C:\Users\user\OneDrive\Desktop\wow\toggle-button...

Done. Now run:

cd toggle-button
npm install
npm run dev

Don’t forget, you can locate your bash or terminal by simply, clicking ctrl+backslash.

# Step 2: Create the ToggleButton Component:

In the `src` directory. create a new file named `ToggleButton.js`. This file will hold our component.

```jsx

import React, { useState } from 'react';
const ToggleButton = () => {
const [isToggled, setIsToggled] = useState(false);
const toggle = () => setIsToggled(!isToggled);
return (
<button onClick={toggle}>
{isToggled ? 'ON' : 'OFF'}
</button>
);
};
export default ToggleButton;

# Step 3: Styling the Button :

To make our button more visually appealing, add some basic styles. Create a `ToggleButton.css` file and import it into your component.

```css

/* ToggleButton.css */
button {
padding: 10px 20px;
font-size: 16px;
color: #fff;
background-color: #007bff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:focus {
outline: none;
}

```

Don't forget to import the CSS file in your `ToggleButton.js`:

```jsx

import ‘./ToggleButton.css’ ;

import './ToggleButton.css';
```

#Step 4: Using the ToggleButton Component:

Now, import and use the `ToggleButton` component in your `App. jsx`.

```jsx

import React from 'react';
import './App.css';
import ToggleButton from './ToggleButton';
function App() {
return (
<div className="App">
<header className="App-header">
<ToggleButton />
</header>
</div>
);
}
export default App;
```

#Step 5: check your toggle button:

Run your application, and you should see your toggle button on the screen. Click it, and it should switch between "ON" and "OFF".

--
And there you have it—a simple toggle button in React.js! This component can be the building block for more complex functionality, such as theme switching or feature toggling. Happy coding!,

--

--