How to import a CSS file in a React Component – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and reactjs. Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about How to import a CSS file in a React Component.
Problem :
I want to import a CSS file into a react component.
I’ve tried import disabledLink from "../../../public/styles/disabledLink";
but I get the error below;
Module not found: Error: Cannot resolve ‘file’ or ‘directory’ ../../../public/styles/disabledLink in c:UsersUserDocumentspizza-appclientsrccomponents @ ./client/src/components/ShoppingCartLink.js 19:20-66 Hash: 2d281bb98fe0a961f7c4 Version: webpack 1.13.2
C:UsersUserDocumentspizza-appclientpublicstylesdisabledLink.css
is the location of the CSS file I’m trying to load.
To me it seems like import is not looking up the correct path.
I thought with ../../../
it would start to look up the path three folder layers above.
C:UsersUserDocumentspizza-appclientsrccomponentsShoppingCartLink.js
is the location of the file that should import the CSS file.
What am I doing wrong and how can I fix it?
Solution :
You don’t even have to name it if you don’t need to:
e.g.
import React from 'react';
import './App.css';
see a complete example here (Build a JSX Live Compiler as a React Component).
You need to use css-loader when creating bundle with webpack.
Install it:
npm install css-loader --save-dev
And add it to loaders in your webpack configs:
module.exports = {
module: {
loaders: [
{ test: /.css$/, loader: "style-loader!css-loader" },
// ...
]
}
};
After this, you will be able to include css files in js.
I would suggest using CSS Modules:
React
import React from 'react';
import styles from './table.css';
export default class Table extends React.Component {
render () {
return <div className={styles.table}>
<div className={styles.row}>
<div className={styles.cell}>A0</div>
<div className={styles.cell}>B0</div>
</div>
</div>;
}
}
Rendering the Component:
<div class="table__table___32osj">
<div class="table__row___2w27N">
<div class="table__cell___2w27N">A0</div>
<div class="table__cell___1oVw5">B0</div>
</div>
</div>
The following imports an external CSS file in a React component and outputs the CSS rules in the <head />
of the website.
- Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
- In webpack.config.js:
module.exports = {
module: {
rules: [
{
test: /.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
}
- In a component file:
import './path/to/file.css';
CSS Modules let you use the same CSS class name in different files without worrying about naming clashes.
Button.module.css
.error {
background-color: red;
}
another-stylesheet.css
.error {
color: red;
}
Button.js
import React, { Component } from 'react';
import styles from './Button.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
class Button extends Component {
render() {
// reference as a js object
return <button className={styles.error}>Error Button</button>;
}
}
The solutions above are completely changed and deprecated. If you want to use CSS modules (assuming you imported css-loaders) and I have been trying to find an answer for this for such a long time and finally did. The default webpack loader is quite different in the new version.
In your webpack, you need to find a part starting with cssRegex and replace it with this;
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
localIdentName: '[name]__[local]__[hash:base64:5]'
}),
}
In cases where you just want to inject some styles from a stylesheet into a component without bundling in the whole stylesheet I recommend https://github.com/glortho/styled-import. For example:
const btnStyle = styledImport.react('../App.css', '.button')
// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.
NOTE: I am the author of this lib, and I built it for cases where mass imports of styles and CSS modules are not the best or most viable solution.
You can also use the required module.
require('./componentName.css');
const React = require('react');
-
Install Style Loader and CSS Loader:
npm install --save-dev style-loader npm install --save-dev css-loader
-
Configure webpack
module: { loaders: [ { test: /.css$/, loader: 'style-loader' }, { test: /.css$/, loader: 'css-loader', query: { modules: true, localIdentName: '[name]__[local]___[hash:base64:5]' } } ] }
You can import css file if css file reside in a same folder where you want to import than just simple try this
import ‘./styles.css’
if css file is far away from our component that navigate that place where file is reside and use this like
import ‘../mainstyles/styles.css’
const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');
You can import your .css
file in .jsx
file
Here is an example –
import Content from '../content/content.jsx';