Skip to content
Advertisement

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement