Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda