4

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.

2 Answers 2

2

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>}
          </>
)
Sign up to request clarification or add additional context in comments.

Comments

1

Try inside your component:

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

...

2 Comments

But in that case, the "third party" css would have to be copied and stored locally. Unless you have an @import to the third party css url in the style.css file.
@Sylhare yea, I'm wondering if there's any way to do it without an html or css file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.