Search code examples
cssreactjscss-modules

Can I use css modules in react class based components?


I have to implement css modules for some older React code. But when I try to import CSS modules, I can´t use this class in another files.

Do I have to refactor the code to React Components? Or is there another easier solution?

Code example:

import styles from "styles.module.css"

var Greeting = createReactClass({
    render: function() {
        return <h1>Hello</h1>;
    }
});

Solution

  • Yes, module CSS is also supported in class-based components.

    In the module CSS you have to use CSS as an object,

    For Example, You have a CSS class for an alert component

    .alert{
       color:red
    }
    

    then you can use it in components like this:-

    import styles from "styles.module.css"
    
    var Alert = createReactClass({
        render: function() {
            return <h1 className={styles.alert}>Hello</h1>;
        }
    });