Search code examples
reactjssasscss-modulesclassname

Is it possible to refer to regular class names using module.css/module.scss?


This might be a dumb question, but I am relatively new to using the CSS/SCSS modules with React.

And I have valid reasons for asking, as modules allow scoping of CSS (which is useful to prevent CSS conflicts), but often when using external libraries (like Material-UI or devextreme) for built-in components, it is needed to override given CSS.

For example (I'll use devextreme for better illustration):

// ...other imports
import Textbox from 'devextreme-react/text-box';

const nameLabel = {'aria-label': 'Demo'}

function App () {
    // imagine a straightforward example,
    return (
        <Textbox placeholder="Demo" inputAttr={nameLabel} />
    )
}

Usually, it is possible to do like below if, for example, I want no padding:

.dx-texteditor.dx-editor-filled .dx-texteditor-input {
    padding: 0;
}

There are surely other ways (like setting id or inline-styling), but it would be great to know if it is possible. Thank you for your kind attention, and all the help.


Solution

  • let see how we can override built-in components css

    • consider you have below a regular css in global-styles.scss file
    .yourRegularClass {
      color: blue;
    }
    
    
    • you can use the :global selector to refer to above global class
    • define your local App.module.css, here the composes keyword is used to compose styles from another component's module
    :global {
      .yourRegularClass {
        font-weight: bold;
      }
    }
    
    
    .myModuleClass {
      color: red;
      
      .dxTexteditornput {
        composes: dxTexteditornput from '~path-to/DevextremeComponent/module.scss';
       padding: 0;
      }
    }
    
    
    
    • update component by importing above local App.module.css. here css class dx-texteditor-input from devextreme-react been overridden
    
    import Textbox from 'devextreme-react/text-box';
    
    import styles from './App.module.css';
    
    
    
    function App () {
        // imagine a straightforward example,
        return (
    
          <div className={styles.myModuleClass}>This is a module class</div>
    
          <div className={`yourRegularClass ${styles.myModuleClass}`}>
            This uses both a global and a module class
          </div>
    
            <Textbox placeholder="Demo" className={styles.dxTexteditornput} />
        )
    }