Home > Enterprise >  React: Conditionally changing image with customHook
React: Conditionally changing image with customHook

Time:12-26

So I have a custom hook that controls the theme (dark/light mode) using tailwind and I have two images that alternate between the two modes. I'm trying to get one to load for darkMode and one to load for lightMode but it doesn't seem to work. I have the FontAwesome icons changing from sun to moon, but the images won't switch. This is the useTheme.tsx hook that changes the title image that controls theme and changeTheme. changeTheme is used in my Theme.tsx component and is essentially a basic button that calls the function onClick.

import { useState, useEffect } from 'react';

export function useTheme() {
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    if (theme === 'dark') {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
    console.log(theme);
  }, [theme]);

  const changeTheme = () => {
    if (theme === 'light') {
      setTheme('dark');
    }
    if (theme === 'dark') {
      setTheme('light');
    }
  };

  return { theme, changeTheme };
}

This is the Title.tsx component where the image is supposed to change based on theme

import { NavLink } from 'react-router-dom';
import { useTheme } from '../../hooks/ThemeHook';
export function Title() {
  const { theme } = useTheme();

  return (
    <NavLink to="/">
      {theme === 'dark' ? (
        <img
          src={'/signature_red.png'}
          alt="signature1"
          key={theme}
          className="min-w-[150px] max-w-[300px] w-1/3 h-[75px]"
        />
      ) : (
        <img
          src="/signature.png"
          alt="signature2"
          key={theme}
          className="min-w-[150px] max-w-[300px] w-1/3 h-[75px]"
        />
      )}
    </NavLink>
  );
}

I've tried messing around with it, removing the useEffect hook and only changing things in changeTheme, setting a helper variable in Title.tsx that gets passed to changeTheme to change the theme in the theme hook. and conditionally changing the src of one image (which I've learned react may not unmount/mount the new component unless the alt changes? which I've also tried) so I'm at a loss for what to try next. Thank you!

CodePudding user response:

you use in hook useTheme in Theme and Title, but is not the same hook, you create two different hooks.

try this(just put the hook in there parent component): codesandboxexample

  • Related