Search code examples
cssreactjstypescriptcss-modules

Use pseudo-classes with imported stylesheet as CSS module


I use React in combination with TypeScript, I have a separate CSS file for each component. I import my CSS file as follows:

import styles from 'pages/login/Login.module.css'

Assigning a className looks like that:

<input className={styles.username} ref={nameRef} type="text"  placeholder="USERNAME"/>

Is there an option to use pseudo-classes?

<input className={styles.username:active} ref={nameRef} type="text"  placeholder="USERNAME"/>

This approach obviously does not work, it is just to make it clearer what I want to achieve.


Solution

  • Once you apply a className, all pseudo-selectors defined in the stylesheet for that CSS class should automatically apply as well.

    Because css modules works by adding classes to your elements you can easily add pseudo class selectors.

    /* component/text.css */
    .text {
      color: #777;
      font-weight: 24px;
    }
    .text:hover {
      color: #f60;
    }
    
    /* component/text.jsx */
    import styles from './text.css';
    
    <p className={ styles.text }>Text with hover</p>
    

    Unfortunately, we cannot apply them one by one.