Open In App

Changing CSS styling with React onClick() Event

Last Updated : 09 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

CSS
/* 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;
}
JavaScript

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.

Peek-2023-10-18-17-08



Next Article

Similar Reads

three90RightbarBannerImg