Sounav Saha
Sounav Saha

Reputation: 85

Is there any method of importing .css files conditionally in React.JS?

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')
);

Upvotes: 1

Views: 3582

Answers (3)

Dylan
Dylan

Reputation: 43

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

Upvotes: 0

Mike Szyndel
Mike Szyndel

Reputation: 10592

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.

Upvotes: 0

elehtine
elehtine

Reputation: 108

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

For example this article explains how use them.

Upvotes: 2

Related Questions