Sometimes, we want to dynamically load a stylesheet with React.
In this article, we’ll look at how to dynamically load a stylesheet with React.
Dynamically Load a Stylesheet with React
To dynamically load a stylesheet with React, we can add a link
element with the attributes we want.
For instance, we write:
import React, { useState } from "react";
export default function App() {
const [stylePath] = useState(
"https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css"
);
return (
<div>
<link rel="stylesheet" type="text/css" href={stylePath} />
</div>
);
}
to create the stylePath
state with the useState
hook.
Its initial value is set to the URL of the stylesheet that we want to include.
Then we add a link element with the href
prop set to stylePath
to add the stylesheet at the given URL into the component.
Conclusion
To dynamically load a stylesheet with React, we can add a link
element with the attributes we want.