Upcoming topics - The Challenge of Staying Hydrated at Basecamp One

I have implemented a themes package for dark mode and light mode in my project. Despite doing the installation correctly as per the repository instructions, I am encountering an issue.

My expected behavior for the project is:

The webpage should initially load based on the user's system settings. The user should then be able to switch between themes using a toggle button.

However, what is happening in my project is:

While the website loads according to the system settings on the first load, the toggle button and the image element in the navigation bar do not reflect this preference. For instance, if the user's system setting is dark mode upon the first page load, the website loads in dark mode but the navbar image element and toggle button icon show up for light mode without following this setting.

How can I resolve this issue?

import Image from "next/image";
import Link from "next/link";
import React, { useState, useEffect } from "react";
import { AiOutlineClose, AiOutlineMail, AiOutlineMenu } from "react-icons/ai";
import { FaGithub, FaLinkedinIn } from "react-icons/fa";
import { BsFillPersonLinesFill } from "react-icons/bs";
import NavLogo from "../public/assets/navLogo.svg";
import DarkNavLogo from "../public/assets/darkNavLogo.svg";
import { useTheme } from "next-themes";
import ToggleButton from "./ToggleButton";

const Navbar = () => {
  const [nav, setNav] = useState(false);
  const [shadow, setShadow] = useState(false);
  const { theme, setTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const handleNav = () => {
    setNav(!nav);
  };

  useEffect(() => {
    const handleShadow = () => {
      if (window.scrollY >= 90) {
        setShadow(true);
      } else {
        setShadow(false);
      }
    };
    window.addEventListener("scroll", handleShadow);
  }, []);

  return (
    <div
      className={
        shadow
          ? "fixed w-full h-20 shadow-xl z-[100] ease-in-out duration-300 px-4 md:px-8 lg:px-16 bg-jelly-bean-50 dark:bg-jelly-bean-950"
          : "fixed w-full h-20 z-[100] px-4 md:px-8 lg:px-16 bg-jelly-bean-50 dark:bg-jelly-bean-950"
      }
          ...
import React, { useState, useEffect } from "react";
import { useTheme } from "next-themes";
import DarkModeIcon from "@mui/icons-material/DarkMode";
import LightModeIcon from "@mui/icons-material/LightMode";

const ToggleButton = () => {
  const [mounted, setMounted] = useState(false);
  const { theme, setTheme } = useTheme();

  useEffect(() => setMounted(true), []);

  return (
    <button
      onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
      className="transition-all duration-100"
    >
      {mounted && (theme === "dark" ? <LightModeIcon /> : <DarkModeIcon />)}
    </button>
  );
};

export default ToggleButton;

Answer №1

There appear to be methods for resolving this issue by leveraging cookies to notify the backend about theme changes, yet I find the syntax elusive.

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

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

The new Facebook login button in my app seems to be glitchy as it fails to redirect users to the appropriate page after

I am working on a web application and have successfully integrated Facebook login from developers.facebook.com. However, I am facing an issue where after the user logs in with their Facebook credentials, they are not redirected to my application. Additiona ...

Next js Link Button with Material-UI Enhancements

Currently, I am working on a project using Server-Side-Rendering React with Next-JS and Material-UI. I am looking to implement a button from Material UI that functions as a Link with Dynamic routes. I am having trouble figuring out how to achieve this. I ...

Can javascript be used to swap out the folder in my URL?

I have been searching for solutions on how to change the language of my website using jQuery, but so far I have not found anything that works for me. Let's take my website as an example: www.domain.com I have separate folders for different languages. ...

Interested in accessing JSON data from another domain? CORS has got you covered

Over at localhost:8080/abc/v1/doc, I get some json data when accessed directly from the browser's address bar. Here are the response headers: Response Headers Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, OPTIONS Cont ...

Dealing with the 'routes not found' error in a Node.js Express application (troubleshooting)

Attempting to address potential missing router errors in my app.js or router file has been a challenge for me. (various solutions found on Stack Overflow have not provided the correct resolution) The current state of my app.js or router files is functiona ...

When a button is clicked, retrieve information from a server using Node.js

In my front end code, I have a scenario where upon clicking a button, I need to retrieve specific data from the node server to populate a map on the client side. The map can be viewed at: "http://localhost:8080/" Here's how I'm making the reques ...

Unable to create a responsive layout because of the use of inline CSS with "margin"

Currently, I am working on a design for a webpage that must be responsive to large, medium, and small screens. To achieve this responsiveness, I am using Material UI Grid container and placing Chips inside it with the style={{ marginLeft: 60 }} from the se ...

Navigating between socket.io and express using while loops

Currently, I am running an express app with socket.io on my raspberry pi to control an LED panel. The panel is being driven by a while loop that updates the pixels. However, I am looking for a way to modify the parameters of this loop or even switch to a d ...

The curious conduct of wild safari creatures

I have been using JavaScript to split my ePub chapter into pages by wrapping the code with new divs that represent separate pages. I have also created CSS styles for these new divs. Everything works perfectly when the file has a filename extension of &apos ...

An issue arises when trying to import the modal popup

Hey there! I'm currently trying to implement a modal popup in react-bootstrap, but I keep running into an error that says "Props not defined". I followed the instructions from the react-bootstrap documentation, but I can't seem to figure out what ...

Show a pop-up form when a user focuses on it using React

Hello, I have been looking for a way to create an overlay with a form that appears when a specific input field is clicked. I am trying to achieve this using React. Can someone please advise me on how to accomplish this? Here is my code import React, { Co ...

Incorporate a JavaScript form into a controller in MVC4

I'm facing an issue where I need to trigger a JavaScript function from within a controller method in my project. Here is the code snippet that I am using: Public Function redirectTo() As JavaScriptResult Return JavaScript("ToSignUp()") E ...

Error encountered during Next.js project build: Entry point specified for implicit type library 'build'

While working on my nextjs project, I encountered the following error: Type error: Cannot find type definition file for 'build'. The file is in the program because: Entry point for implicit type library 'build' Can someone guide ...

Transformed 700 audio players compartmentalized within a nested tab interface. Optimal tab coding techniques include jquery, ajax

We are currently working on developing a nested tab interface that will include 700 audio players for MP3 files all on the same page within various tabs. However, only one audio player will be visible at a time and will only appear when the tab is clicked. ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

The issue with the full postback in the updatepanel is triggered by utilizing JavaScript on the button's onclick event within

During my testing, I encountered an issue with buttons inside a repeater within an update panel. When adding asyncpostback triggers for the buttons using <Trigger></Trigger>, an error is generated indicating that the button could not be found. ...

Transform the React.js class poll component into a React Hooks poll component

I have created a React component "class" based poll, but I am looking to convert it into a React hook form. Can someone please help me with this? I'm having trouble understanding how to achieve this. import React, { Component } from "react"; ...

When clicking in JavaScript, there are two parts to the function, however only one part will work at any given time

I am currently working with two server-side PHP scripts: 1. /addit.php - which generates a PDF file on the server based on the provided ID 2. /viewit.php - which allows the PDF file to be downloaded to the browser window. While both of these scripts are ...

Adjust the spacing between the inputRoot and input in Material UI Autocomplete

Recently, in one of my projects, I've been utilizing Material-UI's Autocomplete component. Despite its lack of flexibility with resizing, I managed to tweak certain width, height, and font size attributes successfully. However, I'm currently ...