1

I need my react project build version to have hashed class names in in html and css. For example if I have:

<div className="test"></div>

I need to be build like this:

<div class="*hashcode*"></div>

can this be achieved in React?

2 Answers 2

1

You need CSS modules.

Create a file named [componentName].module.css with your component. Let us say it looks like:

.divClass {
background-color : red;
}

Import it like a JS object:

import styles from './random.module.css`;

And use it here:

<div className={styles.divClass}></div>

Link to docs

Sign up to request clarification or add additional context in comments.

Comments

0

If you use webpack to build the scaffold from scratch, please continue to read(I assume you had set other configurations done).

Here are the steps

1 set the webpack config file

module.exports = {
...
module: {
      rules: [
         {
          test: /\.(scss)$/i,
          exclude: /node_modules/,
          use: [
            "style-loader",
            {
              loader: "css-loader",
              options: {
                  modules: {
                    exportLocalsConvention: "camelCaseOnly",
                    localIdentName: "[name]__[local]--[hash:base64:5]",
                  },
              },
            },
            "sass-loader",
          ],
        },
...
}

2 create a scss file

// App.scss

.hello {
    color: red;
}

3 Import the scss file and use it.

// App.jsx
import Style from './App.scss';

const App = () => {
    return <div className={Style.hello}>Hello World!</div>
}

Then you should figure it out.

Since you want to add hash to className, you must handle the CSS flow. It would help if you had the tool css-loader. The option localIdentName in modules allows to configure the generated local ident name.

For more info check css-loader

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.