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

238
Views
Created a card that toggles with useState on a list, but it toggles all the items

Here's the component:

import { useState, useEffect } from 'react'

export default function AdminsComponent() {
  const [secondCard, setSecondCard] = useState(false)

  const toggleSetSecondCard = () => {
    setSecondCard(!secondCard)
  }

  const adminsComponent = adminData.map((user) => (
    <li
      key={user.index}
      className="px-4 my-1 lg:pl-8 w-full scale-95 transform transition duration-500 hover:scale-100 text-left"
      onClick={toggleSetSecondCard}
    >
     // codehere
    </li>
      
      {secondCard && (
        <div className="px-4 border-l-4 p-2 bg-accent-0 text-accent-8 pb-4 shadow-lg border-blue">
          // ... codehere
        </div>
      )}

  ))

  return <ul>{adminsComponent}</ul>
}

I removed all the things it have inside to simplify, but basically i created a useState function in which, when i click any of the <li> rendered, it shows the div inside the

{secondCard && ()}

But it is toggling the div for all of the <li> at the same time. I want it individually just for the <li> i clicked. How could i achieve that?

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

0

Each li need to have it's own state. Either by using useState() with an array of boolean mapped to the users, or by having their own component, with their own state, like this:

import { useState } from "react";

const Card = (props) => {
  const [secondCard, setSecondCard] = useState(false);

  const toggleSetSecondCard = () => {
    setSecondCard(!secondCard);
  };

  return (
    <>
      <li
        key={props.user.index}
        className="px-4 my-1 lg:pl-8 w-full scale-95 transform transition duration-500 hover:scale-100 text-left"
        onClick={toggleSetSecondCard}
      >
        {props.user.name}
      </li>
      {secondCard && (
        <div className="px-4 border-l-4 p-2 bg-accent-0 text-accent-8 pb-4 shadow-lg border-blue">
          Hi
        </div>
      )}
    </>
  );
};

export default function AdminsComponent() {
  let adminData = [
    { name: "asger", index: 1 },
    { name: "viggo", index: 2 }
  ];

  return (
    <ul>
      {adminData.map((user) => (
        <Card user={user} />
      ))}
    </ul>
  );
}

The tradeoff with this solution is that one component can't change state in other components, so if you want a "close all" or ensure that only one card is ever shown at a time, you would need the other approach.

Here's an example of how to allow only one open secondCard at a time:

import { useState } from 'react'

export default function AdminsComponent() {
  let adminData = [
    { name: "asger", index: 1 },
    { name: "viggo", index: 2 }
  ];

  const [openCard, setOpenCard] = useState(0);

  return (
    <ul>
      {adminData.map((user) => {
        return (
          <>
            <li
              key={user.index}
              className="px-4 my-1 lg:pl-8 w-full scale-95 transform transition duration-500 hover:scale-100 text-left"
              onClick={() => setOpenCard(openCard == user.index ? 0 : user.index)}
            >
              {user.name}
            </li>
            {openCard == user.index && (
              <div className="px-4 border-l-4 p-2 bg-accent-0 text-accent-8 pb-4 shadow-lg border-blue">
                Hi
              </div>
            )}
          </>
        );
      })}
    </ul>
  );
}
about 4 years ago · Juan Pablo Isaza Report

0

You are using one state element to toggle the entire list.

Problem with the approach is, once the state got toggled, it will be changed for all the elements. Better approach initalize the state as an array and based on index keep shuffling the states.

import { useState, useEffect } from 'react'

export default function AdminsComponent() {
 const [secondCard, setSecondCard] = useState(Array(adminData.length).fill(false))

 const toggleSetSecondCard = (i) => {
   setSecondCard([...secondCard][i]=!secondCard[i]);
 }

 const adminsComponent = adminData.map((user,i) => (
   <li
     key={user.index}
     className="px-4 my-1 lg:pl-8 w-full scale-95 transform transition duration-500 hover:scale-100 text-left"
     onClick={e=>toggleSetSecondCard(i)}
   >
    // codehere
   </li>
     
     {secondCard && (
       <div className="px-4 border-l-4 p-2 bg-accent-0 text-accent-8 pb-4 shadow-lg border-blue">
         // ... codehere
       </div>
     )}

 ))

 return <ul>{adminsComponent}</ul>
}
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!