Next.js Discord

Discord Forum

Dynamically import CSS file depending on a variable

Answered
Spinge Bib Sqorpnts posted this in #help-forum
Open in Discord
Avatar
Hello! I would like to import a specific CSS file depending on a slug's value.
I was wondering if there is a way to do this from a server component?
Current client code looks like this:
useEffect(() => 
  {
    const cssHref = `/colors/${/* SLUG */}.css`;
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = cssHref;

    link.onload = () => setCssLoaded(true);
    link.onerror = () => setCssLoaded(true);

    document.head.appendChild(link);

    return () => 
    {
      document.head.removeChild(link);
    };
  }, []);
Answered by Spinge Bib Sqorpnts
Found out <link> elements can be used in the body to reference stylesheets, but MDN recommends against it.
Image
View full answer

8 Replies

Avatar
Found out <link> elements can be used in the body to reference stylesheets, but MDN recommends against it.
Image
Answer
Avatar
actually, react has a feature where it will automatically detect and hoist your <head> content into the <head>. so if you render <title> in the body, it will detect that and hoist the title to the head. it may happen for <link> too, so try it and see if it works
Avatar
Nope, it appears in <body>
Avatar
then i dont know, sorry
if i were you i would be content with it showing up in <body>, at least that would still load faster than anything you put in useEffect
Avatar
seems to be fast, too
well, I think I'll just keep it in body since it doesn't seem to pose any problem
thank you :)