skip to Main Content

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


  1. 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:

    const handleColorChange = (e: any) => {
      setTheme(themes[myIndex].name.toLowerCase());
      myIndex = (myIndex + 1) % themes.length;
     };
    
    Login or Signup to reply.
  2. Just store the theme index in state. Local variables in a component are not persisted across renders.

    For example:

    const [themeIdx, setThemeIdx] = useState(0);
    // or change this in your useTheme hook
    
    const handleColorChange = (e: any) => {
        setThemeIdx((themeIdx + 1) % themes.length);
    };
    const theme = themes[themeIdx];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search