Conditionally load CSS files in a React project

One way of conditionally load a CSS file in a React component is by using react-helmet. It will manage all of your changes to the document head.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React, { useState } from "react";
import { Helmet } from "react-helmet";

export default function App() {
const [dark, setDark] = useState(false);
return (
<>
{dark ? (
<Helmet
link={[
{
rel: "stylesheet",
type: "text/css",
href: "dark.css",
},
]}
/>
) : null}
</>
);
}

In this case, the CSS file dark.css will only be loaded when dark state is true, otherwise it will not be found in the <head> tag.