How to Switch CSS Class between Buttons Rendered with Map()?

When building web applications, developers often need to create buttons with dynamic styles. One of the most efficient ways to do this is by using the map() method in JavaScript. This method allows you to render multiple buttons with different styles based on their data. However, sometimes you might want to change the CSS class of a button dynamically based on user interaction or other events. In this article, we will discuss how to switch CSS classes between buttons rendered with map() in JavaScript.

Syntax

.button-class {
    property: value;
}

/* Switch classes using JavaScript */
element.classList.add('class-name');
element.classList.remove('class-name');

Algorithm

The algorithm to switch CSS class between buttons rendered with map() involves the following steps

  • Create an array of objects with data for each button

  • Render the buttons using the map() method and assign a default CSS class

  • Add an event listener to each button to listen for user interaction

  • When a user interacts with a button, switch its CSS class to the desired one using the classList property

Method 1: Using State and Ternary Operator (React)

In this approach, we use the useState hook to create a state variable called "activeButton" that will store the ID of the button that is currently active. We then pass this state variable to the className attribute of the button as a ternary operator. If the button's ID matches the activeButton state, we add the "active" CSS class, otherwise, we leave it blank.

import React, { useState } from "react";

const buttonsData = [
   { id: 1, label: "Button 1" },
   { id: 2, label: "Button 2" },
   { id: 3, label: "Button 3" },
];

const App = () => {
   const [activeButton, setActiveButton] = useState(null);
   
   const handleButtonClick = (id) => {
      setActiveButton(id);
   };

   return (
      <div>
         {buttonsData.map(({ id, label }) => (
            <button
               key={id}
               onClick={() => handleButtonClick(id)}
               className={activeButton === id ? "active" : ""}
            >
               {label}
            </button>
         ))}
      </div>
   );
};

export default App;

Method 2: Using Class-based Components (React)

In this approach, we use a class-based component instead of a functional component. We define the state and event handler in the class itself. The rest of the code is almost the same as the previous approach.

import React, { Component } from "react";

const buttonsData = [
   { id: 1, label: "Button 1" },
   { id: 2, label: "Button 2" },
   { id: 3, label: "Button 3" },
];

class App extends Component {
   state = {
      activeButton: null,
   };

   handleButtonClick = (id) => {
      this.setState({ activeButton: id });
   };

   render() {
      const { activeButton } = this.state;

      return (
         <div>
            {buttonsData.map(({ id, label }) => (
               <button
                  key={id}
                  onClick={() => this.handleButtonClick(id)}
                  className={activeButton === id ? "active" : ""}
               >
                  {label}
               </button>
            ))}
         </div>
      );
   }
}

export default App;

Example 1: Switching CSS Class With Click Events

In this example, we will switch the CSS class of a button when the user clicks on it using vanilla JavaScript

<!DOCTYPE html>
<html>
<head>
<style>
    .default {
        background-color: #f0f0f0;
        color: #333;
        border: 1px solid #ccc;
        padding: 10px 20px;
        margin: 5px;
        cursor: pointer;
        border-radius: 4px;
    }
    
    .active {
        background-color: #007bff;
        color: white;
        border: 1px solid #007bff;
    }
    
    .default:hover {
        background-color: #e0e0e0;
    }
</style>
</head>
<body>
    <div id="buttons-container"></div>
    
    <script>
        const buttonsData = [
            { id: 1, label: "Button 1" },
            { id: 2, label: "Button 2" },
            { id: 3, label: "Button 3" },
        ];

        const buttonsContainer = document.getElementById("buttons-container");

        buttonsData.forEach(({ id, label }) => {
            const button = document.createElement("button");
            button.textContent = label;
            button.className = "default";
            button.addEventListener("click", () => {
                const activeButton = buttonsContainer.querySelector(".active");
                if (activeButton) {
                    activeButton.classList.remove("active");
                    activeButton.classList.add("default");
                }
                button.classList.remove("default");
                button.classList.add("active");
            });
            buttonsContainer.appendChild(button);
        });
    </script>
</body>
</html>
Three buttons appear with gray styling. When clicked, the selected button turns blue with white text while others revert to gray.

Example 2: Switching CSS Class With Keyboard Navigation

In this example, we will switch the CSS class of a button when the user navigates to it using the keyboard

<!DOCTYPE html>
<html>
<head>
<style>
    .default {
        background-color: #f0f0f0;
        color: #333;
        border: 1px solid #ccc;
        padding: 10px 20px;
        margin: 5px;
        cursor: pointer;
        border-radius: 4px;
    }
    
    .active {
        background-color: #dc3545;
        color: white;
        border: 1px solid #dc3545;
    }
    
    button:focus {
        outline: 2px solid #007bff;
        outline-offset: 2px;
    }
</style>
</head>
<body>
    <p>Use Tab key to navigate through buttons:</p>
    <div id="buttons-container"></div>
    
    <script>
        const buttonsData = [
            { id: 1, label: "Button 1" },
            { id: 2, label: "Button 2" },
            { id: 3, label: "Button 3" },
        ];

        const buttonsContainer = document.getElementById("buttons-container");

        buttonsData.forEach(({ id, label }) => {
            const button = document.createElement("button");
            button.textContent = label;
            button.className = "default";
            button.addEventListener("focus", () => {
                const activeButton = buttonsContainer.querySelector(".active");
                if (activeButton) {
                    activeButton.classList.remove("active");
                    activeButton.classList.add("default");
                }
                button.classList.remove("default");
                button.classList.add("active");
            });
            buttonsContainer.appendChild(button);
        });
    </script>
</body>
</html>
Three buttons appear with gray styling. When navigating with the Tab key, the focused button turns red with white text while others remain gray.

Conclusion

Switching CSS classes between buttons rendered with map() provides a flexible way to create dynamic user interfaces. Whether using React state management or vanilla JavaScript event listeners, the key is maintaining proper class toggling logic to ensure only one button remains active at a time.

Updated on: 2026-03-15T16:46:55+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements