[javascript] How to import a CSS file in a React Component

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:\Users\User\Documents\pizza-app\client\src\components @ ./client/src/components/ShoppingCartLink.js 19:20-66 Hash: 2d281bb98fe0a961f7c4 Version: webpack 1.13.2

C:\Users\User\Documents\pizza-app\client\public\styles\disabledLink.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:\Users\User\Documents\pizza-app\client\src\components\ShoppingCartLink.js is the location of the file that should import the CSS file.

What am I doing wrong and how can I fix it?

This question is related to javascript reactjs relative-path

The answer is


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.


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 following imports an external CSS file in a React component and outputs the CSS rules in the <head /> of the website.

  1. Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
  1. In webpack.config.js:
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            }
        ]
    }
}
  1. In a component file:
import './path/to/file.css';

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>

  1. Install Style Loader and CSS Loader:

    npm install --save-dev style-loader
    npm install --save-dev css-loader
    
  2. Configure webpack

    module: {
            loaders: [
                {
                    test: /\.css$/,
                    loader: 'style-loader'
                }, {
                    test: /\.css$/,
                    loader: 'css-loader',
                    query: {
                        modules: true,
                        localIdentName: '[name]__[local]___[hash:base64:5]'
                    }
                }
            ]
        }
    

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]'
  }),
}

You can import your .css file in .jsx file

Here is an example -

import Content from '../content/content.jsx';

Using extract-css-chunks-webpack-plugin and css-loader loader work for me, see below:

webpack.config.js Import extract-css-chunks-webpack-plugin

const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');

webpack.config.js Add the css rule, Extract css Chunks first then the css loader css-loader will embed them into the html document, ensure css-loader and extract-css-chunks-webpack-plugin are in the package.json dev dependencies

rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: ExtractCssChunks.loader,
          },
          'css-loader',
        ],
      }
]

webpack.config.js Make instance of the plugin

plugins: [
    new ExtractCssChunks({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ]

And now importing css is possible And now in a tsx file like index.tsx i can use import like this import './Tree.css' where Tree.css contains css rules like

body {
    background: red;
}

My app is using typescript and this works for me, check my repo for the source : https://github.com/nickjohngray/staticbackeditor


You can also use the required module.

require('./componentName.css');
const React = require('react');

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to relative-path

webpack: Module not found: Error: Can't resolve (with relative path) Reading file using relative path in python project How to import a CSS file in a React Component How to open my files in data_folder with pandas using relative path? Relative path in HTML Failed to load resource: the server responded with a status of 404 (Not Found) How does Java resolve a relative path in new File()? relative path in BAT script How to define a relative path in java Relative imports for the billionth time