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

108
Vistas
Is there a way to set the first element in this .map method to a default class on load?

I am currently rendering three buttons using a .map method in React. The buttons are being pulled from an array in a useState.

When clicked, the buttons have a .active class added to them.
How can I set the first element to have the .active class when the page is first loaded?

Current Code: https://codesandbox.io/s/recursing-lake-oetxj?file=/src/App.js

Tried setting the first activeObject to a set variable, but didn't work. I also tried using another useState but couldn't figure out how to link the two. Also tried a useEffect to load the initial state on first render, but couldn't figure out how to link as well.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

What about doing something like this :

  function toggleActiveStyles(index, id) {
    if (buttons.activeObject) {
      return id === buttons.activeObject.id ? "active" : "inactive";
    } else {
      return index === 0 ? "active" : "inactive";
    }
  }

and in HTML. :

  { buttons.objects.map((elements, index) => (
        <button
          key={index}
          className={toggleActiveStyles(index, elements.id)}
          onClick={() => toggleActive(index)}
        >
          {elements.name}
        </button>o

Live demo :
Demo

about 4 years ago · Juan Pablo Isaza Denunciar

0

In my opinion, you should use the ids of your objects to identify them as active or not, it will make your life easier :

when you try to define your classes you are comparing references of the active object and your elements, thus it is to difficult to have a default active one, using ids (number), you can compare the values more easily.

Here is a refactor using ids : https://codesandbox.io/s/elegant-buck-z7ter?file=/src/App.js

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do it with useEffect()

  useEffect(() => {
      toggleActive(0);
  }, []);

https://codesandbox.io/s/vigilant-hopper-4we6k?file=/src/App.js

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