#Dynamically import CSS file depending on a variable

10 messages · Page 1 of 1 (latest)

knotty arch
#

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);
    };
  }, []);
pastel yewBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

knotty arch
#

Found out <link> elements can be used in the body to reference stylesheets, but MDN recommends against it.

robust kraken
robust kraken
#

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

knotty arch
#

well, I think I'll just keep it in body since it doesn't seem to pose any problem

#

thank you :)