I know that I can create my own style content into <style>
tag using style.innerHTML
like this
let style = document.createElement("style");
style.setAttribute("id", "raptors");
style.innerHTML =
".puma {" +
"color: purple;" +
"font-size: 50px;" +
"text-align: left;" +
"}";
However, instead of manually writing css intostyle.innerHTML
, I would like to set the style content by importing styles from local file such as ./styles.css
. So something like this
styles.innerHTML = import `./styles.css`
So I came up with this fetch
solution, but no luck. Is there a solution to this? https://codesandbox.io/s/stylesheet-fetch-experiment-ek4d1h?file=/src/App.js:267-646
let style = document.createElement("style");
style.setAttribute("id", "test");
async function loadCss() {
try {
const response = await fetch("./style.css");
const css = await response.text();
style.textContent = css;
} catch (error) {
console.error(error);
}
}
loadCss();
2
Answers
Instead of creating a
style
element, you could create alink
and set itshref
:Slightly related: https://css-tricks.com/why-isnt-it-style-src/
Import the stylesheet in you component, use the class name. That’s it.
In
Component.tsx
orComponent.js
:In
Component.styles.css
: