generator-react-component
generator-react-component copied to clipboard
How to include CSS with package?
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?
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!
Is @peterh32 answer valid for adding CSS to React-Components ??
any responses @sahilchaddha ?
@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.
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
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.