Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
Set acitve classname to multiple items in react js (map) and remove

I need to set the active classname to multiple onclick items inside a .map

I need the list of active items that were clicked

The items that were clicked will be highlighted in yellow, and when i click the same item again it should be removed from active list items.

const [data, setData] = useState([]);
const [activeIndicies, setActiveIndicies] = useState(() =>
    data?.map(() => false)
);

useEffect(() => {
    // This data is coming from the API response
    const data = [
        { id: 1, name: "one" },
        { id: 2, name: "two" },
       { id: 3, name: "three" }
    ];
    setData(data);
}, []);

return statement

onClick={() => {
    setActiveIndicies(
        activeIndicies.map((bool, j) => (j === index ? true : bool))
    );
}}

Code Sandbox

Thank you.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

try this one:

import "./styles.css";

import React, { useState, useEffect } from "react";


export default function App() {

const [data, setData] = useState([
{ id: 1, name: "one", active: false },
{ id: 2, name: "two", active: false },
{ id: 3, name: "three", active: false }
  ]);

  return (
    <div className="App">
      <h2>Set active className to multiple items on .map</h2>
      {data?.map((item, index) => {
        return (
          <p className={data[index].active ? "selected" : "notselected"}
         onClick={() => {
          setData((prevState) =>
            _.orderBy(
              [
                ...prevState.filter((row) => row.id !== item.id),
                { ...item, active: !item.active }
              ],
              ["name"],
              ["asc"]
            )
          );
        }}
      >
        {item.name}
      </p>
    );
  })}
</div>
  );
}
about 4 years ago · Juan Pablo Isaza Report

0

You can acheive this by simply making some minor changes to your code:

  // Changing the state value to an object so that it can
  // store the active value for exact item ids
  const [activeIndicies, setActiveIndicies] = useState({});

Then inside of .map()

....
        // Checking if there is any value for the item id which is being mapped right now.
        const selected = activeIndicies[item.id];
        return (
          <p
            className={selected ? "selected" : "notselected"}
            onClick={() => {
              /* Then setting the state like below where it toggles 
               the value for particular item id. This way if item is
               selected it will be deselected and vice-versa.
              */
              setActiveIndicies((prevState) => {
                const newStateValue = !prevState[item.id];
                return { ...prevState, [item.id]: newStateValue };
              });
            }}
           // Key is important :)
            key={item.id}
          >
            {item.name}
          </p>
        );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!