1

I'm trying to add a dark-mode in my project. Without React, I would have just targetted the DOM element which triggers the switching of the mode and linked my custom dark.css file instead of index.css which happens to be my pre-dominant CSS file. But here in React, it would take the latest file I'm importing for my CSS. I'm a beginner in React. So please pardon me if this doesn't make much sense. Thanks in advance! Here's my code

import ReactDOM from 'react-dom';
import './index.css';
{/*import './dark.css*/}

import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

3 Answers 3

2

Yes there is a way. You can use React.Lazy and React.Suspense.

For example this article explains how use them.

Sign up to request clarification or add additional context in comments.

2 Comments

Here is maybe easier way.
Medium is asking me to upgrade to read the article, we shouldn't link there
0

There's nothing wrong with importing dark.css every time, but its styles should be applied conditionally. What I mean is, all the styles for dark mode should be wrapped in a CSS class like .dark-mode. Then, when user turns dark mode on, you would apply this class to body tag or to the top-level React component, and remove it when dark mode is turned off.

This will be a much easier solution that trying to work with lazy loading.

Comments

0

For anyone viewing this, I would strongly recommend using useContext. It makes it very easy to pass your theme without using props to all of your children. They even have an example of implementing dark/light theme like you want: https://beta.reactjs.org/reference/react/useContext#usage

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.