Skip to content
Related Articles

Related Articles

Improve 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:

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


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

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

npm start


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

Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML  course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :