skip to Main Content

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


  1. Instead of creating a style element, you could create a link and set its href:

    let link = document.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("href", "./styles.css");
    document.head.appendChild(link);
    

    Slightly related: https://css-tricks.com/why-isnt-it-style-src/

    Login or Signup to reply.
  2. Import the stylesheet in you component, use the class name. That’s it.

    In Component.tsx or Component.js:

    import "./Component.styles.css";
    
    const Component = () => {
      return (
        <div className="myDiv">
          something
        </div>
      );
    }
    

    In Component.styles.css:

    .myDiv {
     color: red;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search