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

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

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

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

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 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