Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 27 Jan, 2021

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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"}]
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!