Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda