Open In App

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

Last Updated : 27 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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"}]

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads