No adjustment in color upon switching themes

I've been struggling to achieve the desired outcome while working on a small coding task. The goal is to modify the color of the screen background, text, and button as illustrated in the uploaded image. I have three code files for this task - index, the custom hook, and the CSS file. Despite updating the commands in local storage upon clicking the "change theme" button, the changes are not reflecting on the screen. Could someone please review the code and suggest a solution?

[see attached image][1]

index.jsx file:

import useLocalStorage from "./useLocalStorage";

export default function DarkWhiteTheme() {
  const [theme, setTheme] = useLocalStorage("theme", "dark");

  const handleToggleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  console.log(theme);

  return (
    <div className="light-dark-mode" data-theme={theme}>
      <div className="container">
        <h1>Hello World</h1>
        <button onClick={handleToggleTheme} className="change-theme-button">
          Change Theme
        </button>
      </div>
    </div>
  );
}

useLocalStorage File:


export default function useLocalStorage(key, defaultValue) {
  const [value, setValue] = useState(() => {
    let currentValue;
    try {
      currentValue = JSON.parse(
        localStorage.getItem(key) || String(defaultValue)
      );
    } catch (error) {
      console.log(error);
      currentValue = defaultValue;
    }

    return currentValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

style.css file


:root {
    --background: #ffffff;
    --text-primary: #000000;
    --button-bg: #000000;
    --button-text: #ffffff;
}

[data-theme='dark'] {
    --background: #000000;
    --text-primary: #ffffff;
    --button-bg: #ffffff;
    --button-text: #000000;
}

.light-dark-mode {
    background-color: var(--background);
    height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 20px;
    transition: all 0.5s;
}

.light-dark-mode .container {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    gap: 30px;
}

.light-dark-mode .container p{
    color: var(--text-primary);
    font-size: 40px;
    margin: 0px;
}

.light-dark-mode .container button{
    background-color: var(--button-bg);
    border: 1px solid var(--button-bg);
    color: var(--button-text);
    padding: 12px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
}

.change-theme-button{
    cursor: pointer;
}

Answer №1

Your code appears to be correct, but the issue lies within your CSS styling. It seems that you have forgotten to include several semi-colons in your declarations.

Make the following adjustments:

:root {
    --background : #ffffff;
    --text-primary : #000000;
    --button-bg: #000000;
    --button-text: #ffffff;
}

[data-theme='dark'] {
    --background: #000000;
    --text-primary: #ffffff;
    --button-bg: #ffffff;
    --button-text: #000000;
}

Answer №2

rather than

export default function useLocalStorage(key, defaultValue) {
  const [value, setValue] = useState(() => {
    let currentValue;
    try {
      currentValue = JSON.parse(
        localStorage.getItem(key) || String(defaultValue)
      );
    } catch (error) {
      console.log(error);
      currentValue = defaultValue;
    }

    return currentValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

attempt

export default function useLocalStorage(key, defaultValue) {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(key);
    return storedValue !== null ? JSON.parse(storedValue) : defaultValue;
  });

  const setStoredValue = (newValue) => {
    setValue(newValue);
    localStorage.setItem(key, JSON.stringify(newValue));
  };

  return [value, setStoredValue];
}

this potential solution could be beneficial

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

Guide to organizing documents using an interface structure

I currently have an interface that outlines the structure of my documents within a specific collection: interface IGameDoc { playerTurn: string; gameState: { rowOne: [string, string, string] rowTwo: [string, string, string] ...

What is the best way to implement a slide-down animation on a stateless component in React JS using either ReactCSStransitionGroup or ReactTransition

I am looking to create an animation for a stateless component that starts off with display:none, and then becomes visible when the parent component's state changes. I want it to slide down like a dropdown menu effect. I am new to animations and have b ...

What is the best way to create a grid layout that is responsive using HTML and CSS

I have been searching all over the internet and have not been able to find a grid layout like this. The "grid-template-columns" property is not achieving what I need, as I cannot make one box larger than the others. I am looking to create 4 equal boxes an ...

Is the sequence of CSS styles important in styling web content?

I'm a newcomer to this field and recently encountered an issue with my div styling. My code was compatible with Chrome 11 but did not render properly in Firefox 4, Opera 11.1, and IE 8. Upon review, I found that the style for the div was as follows, a ...

Fix React/Typescript issue: Exported variable conflicts with name from external module

I am encountering a perplexing issue when using React with Redux and Typescript. The error message I am receiving is unfamiliar to me, and I am unsure how to resolve it. The error states: Exported variable 'rootReducer' has or is using name ...

Error 504 'FUNCTION_INVOCATION_TIMEOUT' encountered on NextJS/Vercel deployment

Encountering an error on one of my pages after deploying to vercel, everything functions properly in dev mode. I suspect the issue lies with one of my fetch/APIs as it utilizes the data from the initial fetch request as the URL for the subsequent fetch re ...

Collaborating on validating inputs and modules for both backend and frontend

Sharing input validation is crucial for various reasons: Immediate feedback to users on the frontend regarding the validity of their input Enhanced security measures in the backend, preventing manipulation of data through the API Dependency on frontend J ...

Javascript code for scrolling to the top isn't functioning as expected

I found a helpful code snippet for adding a scroll to top button on my webpage at the following link: http://jsfiddle.net/neeklamy/RpPEe/ Although I implemented the code provided, unfortunately, the scroll to top button is not displaying correctly. Here ...

Error: AxiosError - Unhandled Promise Rejection due to a Network Error

Currently working on a project using the MERN stack. I am encountering an issue where posts are not loading when accessing the site on localhost via iPhone, but everything is functioning properly on Android devices. Here is a Screenshot of error. const ...

Struggling to align Material-UI Autocomplete and Material-UI FormControl horizontally?

https://i.sstatic.net/PT6IR.jpg Having trouble aligning Material-UI Autocomplete and Material-UI FormControl horizontally. Something seems to be off and I can't figure out what's causing the issue. My goal is to align the Autocomplete component ...

Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required... <button type="button" id= ...

Troubleshooting React and React-Router Link Parameter Issues

I'm a newcomer to React and React Router, and I find myself struggling to grasp several concepts. Any insight or guidance you can provide would be greatly appreciated. I seem to be having trouble getting multiple parameters to work correctly. While I& ...

Error: Unable to access 'map' property of null (TypeError: Cannot read property 'map' of undefined)

Every time I attempt to execute this code, it throws the following error: × TypeError: Cannot read properties of undefined (reading 'map') What is causing this issue? How can I resolve it? import React from 'react'; import Grid from ...

Combining two react functions in a synchronized manner

I'm facing a React coding challenge. I need to combine the handleUpdate and handleUpload functions in a synchronous manner so that the state is updated before the function continues executing. I attempted the following code snippet with my suggested e ...

What is the best way to create a button in React.js using Material UI or a different tool?

How can I create a button similar to the one in this image? It looks like it consists of a button on the left side, but I'm not sure how to create the right side (the arrow figure) with an image and typography inside. Any assistance would be greatly a ...

AWS and Azure are encountering difficulties in successfully executing the build process for a React application

Fixed: The issue was that I had saved my 10400 objects of JSON data as a .js array, causing the build to take too long (I just didn't know how to handle JSON). Switching it to .json format resolved the problem. I developed a React app that functions ...

Retrieving data through the google analytics API for analyzing date metrics

I am currently working on extracting individual dates from the data obtained through the Google Analytics API. My goal is to replicate the functionality of the Google Analytics app. For example, in the Google Analytics app, when there is a date range spec ...

What is the reason behind Firefox's disregard of CSS font-size for code tags within pre tags?

There seems to be a discrepancy in how different browsers on Mac OS X 10.11.4 handle font-size. Is this an issue with Firefox, a CSS bug, or am I missing something about CSS? Here's a JSFiddle where you can see the details. In a section like this: &l ...

Elements within the DIV tag are not displaying in a linear arrangement as intended

I'm having trouble creating a navbar with Bootstrap 4. The items in my div tag are not inline, and I can't align my nav item to the right. Here is the HTML code: <nav class="navbar navbar-inverse "> <div style="display:inline"> ...

The navigation toggler seems to be malfunctioning in the browser, but it is functioning properly on Code

I'm having an issue with my navigation bar toggler. The code works fine in Codeply, but not in the browser. The hamburger button appears on mobile, but the lists are not showing up. Here is the code snippet I'm using: <html> <head> ...