Using a customHook to dynamically swap images in React

Currently, I am facing an issue with a custom hook that manages the theme (dark/light mode) using tailwind CSS. Specifically, I have two images that are supposed to switch based on the theme mode selected. Despite successfully changing FontAwesome icons from sun to moon, the image swapping between darkMode and lightMode does not seem to work as intended. The useTheme.tsx hook handles the switching of the title image based on the theme and changeTheme. The changeTheme function is utilized in my Theme.tsx component through a basic button that triggers the onClick event.

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 };
}

The Title.tsx component is where the image should dynamically change based on the selected 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 made several attempts to resolve this issue, including modifications to the useEffect hook, adjusting only the changeTheme function, introducing a helper variable in Title.tsx to pass to changeTheme for theme changes, and conditionally altering the source of one image. However, despite these efforts, the problem persists. Any suggestions or guidance would be greatly appreciated. Thank you!

Answer №1

When working with hooks in React, it's important to ensure you are using the appropriate hook for each component. In this case, make sure that you are not confusing the useTheme hook with the useTitle hook, as they are two separate hooks.

To resolve this issue, consider placing the hooks in the parent component instead. Check out this example on CodeSandbox: codesandboxexample

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to package a MUI theme along with Rollup?

I have been working on extracting our existing react frontend components from the main repository and moving them into a separate repository that I am bundling with rollup. In our previous code, we used makeStyles which I am now transitioning to styled-com ...

How can I dispatch multiple actions simultaneously within a single epic using redux-observable?

I am a newcomer to rxjs/redux observable and have two goals in mind: 1) enhance this epic to follow best practices 2) dispatch two actions from a single epic Many of the examples I've come across assume that the API library will throw an exception ...

Navigating to a specific page in React Router by passing parameters within

Currently, I am experimenting with a React app that is integrated with a Star Wars API that I have developed locally. The first two routes are functioning properly, but I am encountering issues with the third one. It seems like the second component is int ...

Setting `tabBarVisible` to false does not function properly within a stackNavigation nested element

Details on my project dependencies: "react-navigation": "^3.6.0", "expo": "^32.0.0" I'm working with a TabNavigator that contains redirections to child components, which are StackNavigators. However, I'm facing an issue where I am unable to hide ...

How to Retrieve the href Property of a NextJs Link in a Child Component

I'm currently implementing an interactive button feature using NextJs. Currently, each button is wrapped in a Next link component like this: <Link href={href} key={key} passHref> <MenuItem disableRipple style={{ color: router.p ...

New content appears in Material UI v4 Textfield after being typed

One interesting issue I'm facing is with a list of TextFields on the page where users can input text. The variable data holds the dataset. The problem is, as shown in the gif below, there is a delay in displaying the text after the user types. I initi ...

Toggling visibility in React Native by pressing a button

i have a toolbar in my react-native app that looks like this: https://i.stack.imgur.com/Msu4t.png Whenever I click on the search icon, I want to display an input text field like this: https://i.stack.imgur.com/HPwTB.png I've tried several examples ...

What is the best strategy for managing a sizable react application using react-query?

Since diving into React with functional components and react-query, I've been facing some confusion on how to properly organize my components. Typically, I design components by having a top-level component handle all data access and pass data down to ...

Integrating Next.js with a authentication provider and a Redux provider

During the development of my Next js project, I incorporated Next auth using import {Provider} from 'next-auth/client' to wrap the <Component /> in _app.js. However, I also want to integrate Redux into the project. This involves importing ...

Error 404 occurred when trying to access the webpack file at my website address through next js

Check out my website at https://i.stack.imgur.com/i5Rjs.png I'm facing an error here and can't seem to figure it out. Interestingly, everything works fine on Vercel but not on Plesk VDS server. Visit emirpreview.vercel.app for comparison. ...

ReactJS does not trigger a re-render when changes are made to CSS

I'm curious about the reason why ReactJS does not automatically reapply CSS to child components even when componentDidUpdate() is called. I conducted a small demo where adding a new box doesn't change the color of existing boxes, even though the ...

Cannot read property 'focusVisible' of null error is occurring on the radio

Having a complex setup involving Gatsby 1.9, react-next, React 16.5.2, and Material UI 3.2.2. Encountering issues with Radio and RadioGroup components consistently causing a strange error to pop up (refer to the image below). Unfortunately, unable to upg ...

Change the size of a custom cursor on click using React

I have customized the cursor on my react app, but I want to make it animate when the user clicks. Perhaps by decreasing its size or some other effect. The cursor is within a component that I've included in my Index.js file. I am unsure how to create a ...

Enhance the appearance of Google Maps by incorporating gradient effects, box shadows, or other similar visual

How can I add a linear gradient to Google Maps? Below is my code snippet. HTML <div id="map"></div> CSS #map{ height:100vh; background: linear-gradient(90deg, #f7f8fa 0%, rgba(247, 248, 250, 0) 18.73%), linear-gradient(180deg, # ...

Error encountered when trying to connect Solidity contract with React Next.js, issue with fetching contract through NPM package

My goal is to create an NFT marketplace, but I've encountered a problem with npm run dev. It was working fine yesterday, but now it's not letting me fetch functions from NFTMarketPlace.sol after exiting VSCode. I tried deleting node_modules & ...

How to retrieve the user-agent using getStaticProps in NextJS

Looking to retrieve the user-agent within getStaticProps for logging purposes In our project, we are implementing access and error logs. As part of this, we want to include the user-agent in the logs as well. To achieve this, we have decided to use getSta ...

Determine with jQuery whether the img src attribute is null

My HTML structure is as follows: <div class="previewWrapper" id="thumbPreview3"> <div class="previewContainer"> <img src="" class="photoPreview" data-width="" data-height=""><span>3</span> </div> </div> ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

Exploring the functionality of CSS class selectors (.class-name) when used alongside CSS tag selectors (div, etc...)

I have designed my website with three distinct tables, each requiring unique styling. The general approach I take to apply styling to these tables is as follows: import './gameview.css' <div className="game-results"> <h ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...