I am trying to create a button that loops through a specific set of themes when pressed. Also, after displaying the last theme, it would loop back to the beginning of the array. I created a handle function that would loop through the various themes by updating the custom react hooks function useThemes. However, my attempt is not producing any results. Here is my code, thank you for any help.
const { theme, setTheme } = useTheme();
const themes = [
{ name: "Normal" },
{ name: "Dark" },
{ name: "Forrest" },
{ name: "Pink" },
{ name: "Sky" },
{ name: "Strawberry" },
];
let myIndex = 1;
const handleColorChange = (e: any) => {
setTheme(e.themes.name[myIndex].toLowerCase());
myIndex = (myIndex + 1) % themes.length;
};
<button onClick={handleColorChange}>
</button>
2
Answers
The issue is in the handlerColorChange method, you are trying to get a property that doesn’t exist in the
e
variable, I think you meant to get it from the themes array instead.Try this:
Just store the theme index in state. Local variables in a component are not persisted across renders.
For example: