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

166
Visualizações
React. How to change state only to current element after .map method?

When all list items are rendered I want that after click only clicked list item has been changed its style.

const [currentStyle, setCurrentStyle] = useState();

array.map(val => (<li style={currentStyle}>{val.name}</li>)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I advise you to make another component for you items, that way it will be easier to manage state for each item

for instance :

function YourComponent() {    
...
const [currentStyle, setCurrentStyle] = useState();
    ...
    array.map(val => (<ItemComponent style={currentStyle}>{val.name}</ItemComponent>)
...
}

function ItemComponent({style, children}) {
   const [changeStyle, setChangeStyle] = useState(false)
   return (
       <li onClick={() => {setChangeStyle(true)}} style={changeStyle ? style : null}>{children}</li>
    )
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The better way to do that has already been shared by Jimmy. but if you are lazy you can do something like.

Note: Both approaches are different. If you manage that via subcomponents you will have to add extra logic to keep track of clicked items in the parent. (Still recommended)

But if you use this one you can have the clicked Items track in the component itself (clickedItems)

const [currentStyle, setCurrentStyle] = useState();
const [clickedItems, setClickedItems] = useState([]);

array.map((val, index) => (<li onClick={() => 
    setClickedItems(clickedItems.find(i => i===index) ? clickedItems : [...clickedItems, index])}
    style={clickedItems.find(i => i===index) ? currentStyle : null}>{val.name}
</li>)
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