Friday, November 21, 2025
HomeLanguagesJavascriptHow to switch CSS class between buttons rendered with map()?

How to switch CSS class between buttons rendered with map()?

We can change the color of a button when it gets clicked, and also change the color of the previously selected button back to its initial original color using the map() function.

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: It will look like the following.

Project Structure

Example: In the following example, we have stored the currently selected button’s name (or some ID) in the state.

Filename: App.js

HTML




import React, { useState } from "react";
  
const App = () => {
  const menuItems = ["Easy", "Medium", "Hard"];
  const [activeButton, setActiveButton] = useState("");
  
  return (
    <div>
      {menuItems.map((level, idx) => {
        return (
          <button
            key={level}
            onClick={() => {
              setActiveButton(level);
            }}
            style={{
              backgroundColor: activeButton === level ? "lightblue" : ""
            }}
          >
            {level}
          </button>
        );
      })}
    </div>
  );
}
  
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: 

Color Switches between the button on Click

Note: One thing we should take care of is to name the buttons differently. Also, a more encouraging way to do this is to use IDs for buttons like shown below:

const menuItems = [{id:1, name:"Easy"}, 
                        {id:2, name:"Medium"}, 
                        {id:3, name:"Hard"}]
RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7164 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS