Dynamically import CSS file depending on a variable
Answered
Spinge Bib Sqorpnts posted this in #help-forum
![Avatar](https://cdn.discordapp.com/avatars/332567411620577280/dd5f9fddf3e5dcb6102949df26064d7b.webp?size=256)
Spinge Bib SqorpntsOP
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:
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](https://cdn.discordapp.com/attachments/1221363492385194065/1221366415672610836/image.png?ex=6612511d&is=65ffdc1d&hm=0135aa0d4990f97128f7750fe0af5c2de773b04fb1cba695fb3705d70d78474d&)
8 Replies
![Avatar](https://cdn.discordapp.com/avatars/332567411620577280/dd5f9fddf3e5dcb6102949df26064d7b.webp?size=256)
Spinge Bib SqorpntsOP
Found out
<link>
elements can be used in the body to reference stylesheets, but MDN recommends against it.![Image](https://cdn.discordapp.com/attachments/1221363492385194065/1221366415672610836/image.png?ex=6612511d&is=65ffdc1d&hm=0135aa0d4990f97128f7750fe0af5c2de773b04fb1cba695fb3705d70d78474d&)
Answer
![Avatar](https://cdn.discordapp.com/avatars/484037068239142956/f386ac21405ce3442e0f3598223e1cb3.webp?size=256)
joulev
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](https://cdn.discordapp.com/avatars/332567411620577280/dd5f9fddf3e5dcb6102949df26064d7b.webp?size=256)
Spinge Bib SqorpntsOP
Nope, it appears in
<body>
![Avatar](https://cdn.discordapp.com/avatars/484037068239142956/f386ac21405ce3442e0f3598223e1cb3.webp?size=256)
joulev
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](https://cdn.discordapp.com/avatars/332567411620577280/dd5f9fddf3e5dcb6102949df26064d7b.webp?size=256)
Spinge Bib SqorpntsOP
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 :)