Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!