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.
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
You can do it with useEffect()
useEffect(() => {
toggleActive(0);
}, []);
https://codesandbox.io/s/vigilant-hopper-4we6k?file=/src/App.js
CodePudding user response:
I think useEffect is the way to go here, you already have the method to set the class to active, you just need to call it inside the useEffect hook so it gets called when the component first renders with the params you want. Something like this:
useEffect(()=>{
//here we set the default class
toggleActive(0, buttons.objects[0].name)
}, [])