| 0 | kirasiris | Categories: Tags: , ,

React

Problem? Loading files…

Damn, I literally spent about two hours trying to hijack xD React core base to be able to’dynamically’ load style-sheets files in certain pages but it was just not working – well, it did but it was messing with the design from other components – which was something that was pissing me off, like I mean – for real – I wanted to punch my screen for the first time(I’m a very chill and calmed person, I don’t get frustrated, angry, etc that easily; that says a lot about having a shitty day, don’t you think?)

There were several solutions out there on Internet – a.k.a StackOverflow – but they just did not fit to my needs, besides the fact that most developers kept using class components(I hate them and they’re a mess to work with with complex state management) instead of Hooks :/….move the fuck on, Hooks are the new standards!.

Then I suddenly though about useEffect, that little shit that sometimes gets in my nerves as well. useEffect usually loads before the browser and after a certain action is triggered(as long as you pass the X function as a second parameter of course useEffect(()=>{Yada()},[yada])); and that just made me realize that using it could be a good solution to my needs so here they are!.

Explaining The Solution

We first begin by creating a function that takes two parameters; in our case these are both strings. Actually on this code(the CSS one), you only need the first parameter since CSS usually goes within the <head></head> section of a web page but well….who cares?!; I made it possible to control its position; you can either use head or body.

The code is shown below but it you find it difficult to read because of my current dark theme that I’m using on this website, then feel free to check my GitHub Gist in which I just created these two files as well and please READ the comments.

useCSS.js
import { useEffect } from 'react';

const useCSS = (url, position) => {
  useEffect(() => {
    const placement = document.querySelector(position);
    const link = document.createElement('link');

    link.href = url;
    link.rel = 'stylesheet';

    placement.appendChild(link);

    return () => {
      placement.removeChild(link);
    };
  }, [url, position]);
};

export default useCSS;
useScript.js
import { useEffect } from 'react';

const useScript = (url, position, async) => {
  useEffect(() => {
    const placement = document.querySelector(position);
    const script = document.createElement('script');

    script.src = url;
    script.async = typeof async === 'undefined' ? true : async;

    placement.appendChild(script);

    return () => {
      placement.removeChild(script);
    };
  }, [url, position, async]);
};

export default useScript;

Bye-Bye 🙂

Leave a Reply

Back to Top