generator-react-component icon indicating copy to clipboard operation
generator-react-component copied to clipboard

How to include CSS with package?

Open adrianmcli opened this issue 8 years ago • 6 comments

I admit this is a bit of a newbie question. I'm making a simple React Component that also depends on a CSS file. How do I make it so that the CSS file is included automatically when people install and require the NPM package?

adrianmcli avatar Mar 19 '16 06:03 adrianmcli

Here's what I did @adrianmcli : Create a file in src: MyComponent.css.js, containing this code

export default ` 
.my_component {
    color: green;
    font-size: 20px;
   ... more css here...
`;

Note the backticks so it exports the css as a big multiline string.

Then in my component js:

import cssStyles from './MyComponent.css';

...and in my render method:

    if (!document.getElementsByTagName('head')[0].querySelector('style[id="my-component"]')) {
      // insert the style into the head
      let tag = document.createElement('style');
      tag.id = 'my-component';
      tag.innerHTML = cssStyles;
      document.getElementsByTagName('head')[0].appendChild(tag);
    }

Voila!

peterh32 avatar Jan 26 '17 18:01 peterh32

Is @peterh32 answer valid for adding CSS to React-Components ??

sahilchaddha avatar Apr 03 '17 11:04 sahilchaddha

any responses @sahilchaddha ?

adutta91 avatar Aug 31 '17 02:08 adutta91

@adutta91 Yes it is, but its not the recommended way. Its a workaround to save css in string format and inject it directly into html. This does not minify CSS.

sahilchaddha avatar Aug 31 '17 11:08 sahilchaddha

Hi, Did anyone solve it so far? also, is it possible to also load .png files? in my react component (created with create-react-app) I used both css and png

lucascassiano avatar Nov 03 '17 18:11 lucascassiano

Just a note: I kinda solved the .css and .png problem: -for css: just copy your .css files into /dist/ and make sure on the README.md page explains how to directly import them, e.g.


Import 'myComponent/dist/css/myStyle.css';

-for png and svg: Just convert the files to base64 and add them directly to your code, use something like: https://www.base64-image.de for png or http://b64.io for svg to parse the files, I know.. it's not the fastest way, but it works.

lucascassiano avatar Nov 03 '17 21:11 lucascassiano