hustle100
hustle100

Reputation: 73

Can you import an external CSS file in a React js file?

I'm using a third party library installed through npm, but it requires an external stylesheet if you want to use its styles. I only want to load the styles on a certain page though and don't want to include it in the main html file. We use Material-UI and don't have any style sheets either so is there a way to import it directly from my component's js file?

I tried including it in the return but to no avail.

return (
<div>
<link
      rel="stylesheet"
      href="//fake.net/thirdpartylibrary.js/latest/thirdpartylibrary.min.css"
    />
</div>
)

I've also tried appending the stylesheet to the document head from within my component and it does add it, but does not load in time.

 const linkElement = document.createElement("link");
      linkElement.setAttribute("rel", "stylesheet");
      linkElement.setAttribute("type", "text/css");
      linkElement.setAttribute(
        "href",
        "//fake.net/thirdpartylibrary.js/latest/thirdpartylibrary.min.css"
      );
      document.head.appendChild(linkElement);

edit: It works if I wrap the above in a useEffect hook and add a state value that is set to true after the stylesheet is appended to the document head.

Upvotes: 4

Views: 7520

Answers (2)

hustle100
hustle100

Reputation: 73

wrapped in a useEffect hook and add a state value that is set to true after the stylesheet is appended to the document head.

const [isLinkElementLoaded, setLinkElementLoaded] = useState(false)

    useEffect(() => {
    const linkElement = document.createElement("link");
          linkElement.setAttribute("rel", "stylesheet");
          linkElement.setAttribute("type", "text/css");
          linkElement.setAttribute(
            "href",
            "//fake.net/thirdpartylibrary.js/latest/thirdpartylibrary.min.css"
          );
          document.head.appendChild(linkElement);

          setLinkElementLoaded(true)
    }, []);

return (
          <>
            {isLinkElementLoaded && <div>Styled Component</div>}
          </>
)

Upvotes: 2

Tomasz Nguyen
Tomasz Nguyen

Reputation: 2611

Try inside your component:

import React from 'react';
import './style.css';

...

Upvotes: 1

Related Questions