user13468285
user13468285

Reputation:

Dynamically importing css files into react

i am wondering is there a way to dynamically import a css file into react. say i have a css file named style-light.css and i have another named style-dark.css. is there a way to use react state or some other method to dynamically import the css files into the component based on the current value of the state ? eg

import "../style-light.css" // default import


export default function TestImport(){
const [switch, setSwitch] = useState("light");

if(switch === "dark"){
import "../style-dark.css" // adds the style-dark import below the light one to overwrite the light css.
}

return (
<div>
<button onClick={()=> setSwitch("dark")}> click to get dark css </button>
</div>
)
}

bascially something like that? any insight will be helpful. thanks

Upvotes: 3

Views: 3629

Answers (1)

Carlos Silva
Carlos Silva

Reputation: 56

Option 1

For that I would recommend that you use CSS variables and only one CSS file. You can change the values of your variables based on a class applied on your page body. For example:

variables.css

:root {
    --textColor: black;
}

[class="dark-theme"] {
    --textColor: white;
}

With javascript you can add or remove the class from your html document, like this

component.js

document.documentElement.classList.add('dark-theme')
document.documentElement.classList.remove('dark-theme')

On your components styles you can use the variables with var(--variable)

component.css

.my-component-class {
  color: var(--textColor);
}

Option 2

Use some CSS-IN-JS library like styled-components or emotion, you can use a ThemeProvider to change our theme accordingly with some state in your application. See this example here: https://styled-components.com/docs/advanced#theming

Upvotes: 3

Related Questions