CSS Loader in ReactJS

ReactJSWeb DevelopmentFront End Technology

In this article, we will learn how to provide dynamic class names to our React application.

Steps

Npm run eject

This command will allow us to customize the configurations and the options that were predefined when we run the command of create-react-app. It is a one-sided operation that can’t be undone later on.

Change Webpack configurations

We need to configure the webpack loaders so as to enable css-loader which will then provide dynamic naming to our classes.

Set the configurations as −

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

Import css files dynamically

import styles from './App.css'

Example

In this example, we will build a React application that has dynamic naming to the classes of the JSX elements.

App.jsx

import React from 'react';
import styles from './App.css'
const App = () => {
   return (
      <div classname={styles.App}>
      <h2>TutorialsPoint</h2>
      </div>
   );
};
export default App;

In the above example, a dynamic class name is provided to the <div> tag.

Output

raja
Published on 18-Mar-2021 10:31:51
Advertisements