React Suspsense fails to load the stylesheet

I'm currently working with the following code snippet.

<Suspense fallback={<span />}>
  {theme === "dark" ? <DarkTheme /> : <LightTheme />}
</Suspense>

DarkTheme Component

import React from "react";
import "./dark-theme.css";
const DarkTheme = () => {
  console.log("Loading dark theme...");
  return <></>;
};

export default DarkTheme;

LightTheme Component

import React from "react";
import "./light-theme.css";

const LightTheme = () => {
  console.log("Loading light theme...");
  return <></>;
};
export default LightTheme;

Currently, when switching to dark mode, the DarkTheme component and its css load correctly. However, when switching back to light mode, the LightTheme component loads but its css does not load.

Switching to dark mode: [Click here] (https://i.sstatic.net/hZhmi.png)

Switching back to light mode: [Click here](https://i.sstatic.net/hSw2Z.png) You can view the full code here.

Answer №1

It seems like you're confusing css imports with conditional rendering in React js!

The condition

{theme === "dark" ? <DarkTheme /> : <LightTheme />}
only impacts react elements rendered within Suspense. However, importing a css stylesheet will remain attached to your DOM. This can lead to a clash between the light theme and dark theme when switching themes.

To switch between dark mode and light mode, consider using conditional style props such as:

 <div style={theme === 'dark' ? {background:'black'} : {background:'white'}}>
  {children}
  </div>

Add this code to your main component (App).

Take a look at css modules for an easier solution.

Answer №2

Dealing with a similar problem in the past, I came across a helpful resolution on a StackOverflow thread: Dynamically load a stylesheet with React. Rather than dynamically loading a CSS file, you could explore adjusting the color scheme of your design instead.

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

Ways to prevent onMouseDown from triggering when the element is exclusively clicked?

I'm currently working on developing a game where units (svg elements) are controlled using React. In this game, the units should be draggable, and clicking on a unit should open a form. However, when I click on the unit, only the mousedown event is t ...

Select the dropdown menu to access the last line of the table

My custom dropdown is causing a scroll to appear at the bottom of the table when it's open, making it hard to view all the elements. I want to find a way to either expand the body of the dropdown or enlarge it so that this doesn't happen. Can any ...

Achieve a scrolling effect for just a specific section of an HTML page

Hey there! I'm currently working on adding scrolling text along the side of a webpage for a specific section. My goal is to have three different sections, each with text that stops scrolling when you reach it and then transitions to the next section o ...

What is the best way to place an icon in the lower right corner of a design

I have encountered an issue while building the testimonial section below. The problem arises when the amount of text in each block is not the same, causing the quote icon to be displayed improperly in the bottom right corner. Sometimes, it even extends out ...

Use next-i18next's Trans component to render a link as `[Object object]` instead of displaying the proper link

I encountered an issue with interpolation in the Trans component of next-i18next. Instead of displaying a proper link, I am seeing [Object object]. When I inspect the translation value in React Developers Tools, everything appears to be correct. Here is h ...

A comprehensive guide on retrieving data from API across several pages

Struggling with pulling data from an API using React and facing the challenge of retrieving more than one page of data. "info": { "count": 493, "pages": 25, "next": "https://rickandmortyapi.com/api/character/?pa ...

The Bootstrap column is causing a cropping issue on the left side of my rows

I'm currently working on a Python/Flask/HTML project that utilizes Bootstrap 4 for a grid system with multiple rows and columns. However, when I attempt to run the project, a few pixels get cut off on the left side of the screen. I've thoroughly ...

Implementing modifications to all HTML elements simultaneously

In my HTML document, there are around 80 small boxes arranged in a grid layout. Each box contains unique text but follows the same structure with three values: name, email, and mobile number. I need to switch the positions of the email and mobile number v ...

× Unmanaged Error (TypeError): JSON input ended unexpectedly

I am facing an issue with an if statement that checks whether an access token is defined, and if so it proceeds to execute two fetch requests. The first fetch request retrieves the desired information successfully. However, I am encountering an error when ...

Error: The reselection failed because the selector creators require all input selectors to be in the form of functions

I am in the process of incorporating reselect into my component: const test = useSelector(({ test }) => test); const testData = createSelector( test, items => console.log(items), ); I encountered an issue with Error: Selector creators ...

retrieve the position of a descendant element in relation to its ancestor element

I'm encountering a challenge while attempting to solve this issue. I have elements representing a child, parent, and grandparent. My goal is to determine the offset position of the child (positioned absolutely) in relation to the grandparent. However, ...

What is the best way to position an element on the left side of the navbar without having it animated?

Could someone assist me in placing the Life's Good logo on the left side of the nav bar without applying the animation from the "btn" class? Below is a snippet of my code with an example where I want the logo highlighted in Yellow: * { padding:0; m ...

Position card boxes in the center using bootstrap

Hey there! I'm facing an issue with my two cards (check out the image below) https://i.sstatic.net/XDWop.png It seems like the card boxes are not perfectly centered. I've made some adjustments in the code snippet provided. Could you please lend ...

The returned state from setState(prev) seems to be in the opposite order when referencing another useState variable within a useEffect

As part of my interactive chat simulation project, I have implemented a feature where users can click on a button named obj4 to start their chat session. Initially, everything functions smoothly, displaying messages 1-4 in the correct order. However, when ...

Create a grid layout similar to Bootstrap by utilizing the Material-UI Grid list component

Looking to make the transition from Bootstrap to Material-ui in my ReactJS project. I have a JSFiddle showcasing a 2-column panel with a header using Bootstrap. How should this be coded using React Material-UI? https://i.stack.imgur.com/ONDwb.png The goa ...

What is the best way to adjust the color of the colon within my timer digits using a span element?

I am facing an issue with my timer where the span that was created to display a colon between the numbers does not change color along with the timer digits. I attempted using var colon = document.getElementById(":"); but it still did not work as expected. ...

Filtering Data with React and Highcharts

My goal is to implement the functionality of Highstock rangeSelector for all highcharts modules, such as word cloud and pie charts. When I select a time range like 1m in Highstock, I want it to filter the data in other charts accordingly. Since I couldn&a ...

Tips for showcasing boxed numerical characters on a website

Currently, I am tackling a project that involves converting a PDF into HTML. The original .ai file shows some numeric characters inside a box: https://i.sstatic.net/dAMU2.png Even though I am aware that the font used in the file is GothicMB101Pro DeBold- ...

Neglect the RequestBody parameter depending on the specified criteria

When passing an object and receiving it with a RequestBody annotation of the Spring Framework, there is a desire to include a value for a hashmap as a key-value pair in the object's POJO. Additionally, there is also an ENUM as a second variable. The ...

The sequence of Bootstrap columns collapsing into place

My first Bootstrap website is causing me some trouble. Currently, the content under the main jumbotron appears in a specific order on a full 1920x1080 page: Statement Image Image Statement Statement Image However, when the website collapses to mo ...