How to load CSS file based on condition using ReactJS hook?

ReactJS hook made front-end code writing more functional. As we know pure functions are stateless and have fewer side effects. In our case, we had multiple sites using the same code base. Each site wanted to load a custom CSS that can overwrite common CSS. Here is how we solved it using ReactJS hook:

const Output = () => {
  const { siteName } = useContext();

  const willMount = useRef(true);
  if (willMount.current && siteName) {
    try {
      // eslint-disable-next-line global-require, import/no-dynamic-require
      require(`./customStyles/${siteName}-custom.css`);
    } catch (e) {
      console.log(e);
    }
    willMount.current = false;
  }
}

Now all we need is to create a CSS file inside customStyles directory and we will load the custom CSS.

Share