Nately Jamerson
Nately Jamerson

Reputation: 313

import css using webpack in react

I was from angularjs, now picking up react. Even I was using angular 1.x which is already component based, but it still has template. But in react the file structure and the way we use to code front end has changed, like instead of spiting files by pages, u make files by component now. It promotes reusability but does that means how we apply the css also changed?

I saw this import { navBar } from 'styles/navbar.css' in navBar.jsx. Hmm how does css work together with JSX? doest navBar css load that file? What webpack plugin is needed for that? does it come from default? I'm using react-create-app by facebook so I didn't know much about config.

Upvotes: 3

Views: 1463

Answers (2)

felixmosh
felixmosh

Reputation: 35573

This kind of import { navBar } from 'styles/navbar.css' is not relevant to JSX but to css-loader. This is a webpack loader that handles css, and it supports cssModules, that allows you to encapsulate selector names in order to avoid css leaks.

So, shortly, that import exposes an object with mapping between your selector to unique string (usually an a hash).

For example:

// styles.css
.foo {
   color: red;
}

.bar {
   color: green;
}


// Component.jsx
import styles from './styles.css';

console.log(styles);
/* This will print something like
{
  foo: '_h234jh',
  bar: '_234m23'
} 
*/

Upvotes: 0

Assan
Assan

Reputation: 428

You use css-loader and style-loader to include CSS files in your webpack bundle. By default it generates some JavaScript code that creates a style element with the contents of the imported CSS file and appends it to the head element in your index.html.

So you can definitely use external CSS files to style your React components, just make sure that every CSS class is properly namespaced to avoid naming conflicts with the classes of other components.

For example you could adopt the BEM naming scheme. If your component is called NavBar, then the root element of that component might have a className of x-nav-bar (the x prefix is there to avoid clashing with frameworks like bootstrap), and all child elements, if they need to be styled, will then have class names like x-nav-bar__${childName}.

Upvotes: 1

Related Questions