Load dyanmic css file in react


#1

I have path of css file in settings.json.
I am use following code:-

var str = Meteor.settings.public?Meteor.settings.public.customCSS:'../style/style.css';
require(str)

And in ‘Meteor.settings.public.customCSS’, I have this path “/public/styles/siegelvision.css”.

It gives ‘Error: Cannot find module ‘/public/styles/siegelvision.css’’

Please advice how i can use this css path from json in require.


#2

There are many different ways you can handle this; here’s one quick example. Add the logic to load the CSS path/name from your settings (with fallback) to a new custom component like:

import React from 'react';
import { Meteor } from 'meteor/meteor';

const CustomCss = () => {
  let customCss = Meteor.settings.public.customCSS;
  if (!customCss) {
    customCss = '/style/style.css';
  }
  return (
    <link rel="stylesheet" type="text/css" href={customCss} />
  );
};

export default CustomCss;

Then reference this component wherever you need it in your app. For example:

import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import React from 'react';

import CustomCss from '../imports/ui/components/CustomCss';
... other components ...

Meteor.startup(() => {
  render(
    <div>
      <CustomCss />
      ... other components ...
    </div>,
    document.getElementById('app')
  );
});