Changing CSS styling with React onClick() Event
Changing CSS styling with React onClick() Event simply means changing the CSS property or CSS classes when the click event triggers. It can be done by switching the states to update the classes when a button is clicked
Prerequisites
Approach
Changing CSS styling with React onClick() Event we will use useState variable. We will change the background and color of a container by making use of the onClick() event. We will initially define the CSS for our app. Once a user clicks the button the background color gets changed by changing the state. Implementing dynamic styles based on user interactions is key to creating engaging applications.
Now, let’s get started with the file structure and coding part.
Creating React App
Step 1: Create a React application using the following command:
npx create-react-app appname
Make sure that the app name is starting with lower-case letters.
Step 2: After creating your project folder. Now, jump into the respective folder by making use of the following command:
cd appname
Project Structure: Now, the file structure will look like the following:
Our app file Structure
Example: Using useState variable to update the class name on click event to switch the style of component between light and dark mode.
/* Filename - App.css */
.App {
text-align: center;
}
.geeks {
color: green;
}
.light {
color: red;
background-color: white;
}
.dark {
color: lightgreen;
background-color: gray;
}
button {
font-size: large;
margin: 2%;
background-color: green;
color: white;
border-radius: 5px;
padding: 10px;
}
// Filename - App.js
import React, { useState } from "react";
import "./App.css";
const App = () => {
const [style, setStyle] = useState("light");
const changeStyle = () => {
console.log("you just clicked");
if (style !== "light") setStyle("light");
else setStyle("dark");
};
return (
<div className="App">
<h1 className="geeks">GeeksforGeeks</h1>
<h3 className={style}>
CHANGE CSS STYLING WITH ONCLICK EVENT
</h3>
<button
className="button"
onClick={changeStyle}
>
Click me!
</button>
</div>
);
};
export default App;
Step to run the application: Run the code by making use of the following command:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. After, onClick component switches to dark and light mode.