简体   繁体   中英

How to use SASS parent selector with sass module in react

Consider the following

styles.module.sass

 .button
     cursor: pointer
     background: transparent
     &.active
       border-left-color: green
       border-left-width: 2px

Button.js

const MyButton = () => {
    return <button className={styles.button}>select this</button>;
};

How can attach the .active class inside of the className given that this is a scss module? The following wont work, as the 'active' is not in the context of the class name re-writing.

const MyButton = () => {
    return <button className={styles.button + "active"}>select this</button>;
};

Just pick the active class from styles too like styles.active and have a space between classes when joining. For that, you can do any of the following:

  1. You can use change to className={styles.button + " " + styles.active} or use template string:
const MyButton = () => {
    return <button className={`${styles.button} ${styles.active}`}>select this</button>;
};
  1. You can use classnames
import classNames from 'classnames'
const MyButton = () => {
    return <button className={classNames(styles.button styles.active)}>select this</button>;
};
  1. You can use patch-styles component:
const MyButton = () => {
    return (
        <PatchStyles classNames={styles}>
            <button className="button active">select this</button>
        </PatchStyles>
    );
};

I personally prefer patch-styles or sometimes classnames combined with patch-styles . As patch-styles brings a big abstraction to your code, you don't need to care about applying styles to every place and missing it when applying the active class. It also allows moving to or from CSS/SCSS modules by changing just a few code lines.

About the benefits of using classnames , read their documentation. It's handy when you have classes which depend on certain conditions.

You could use Composition

.button
     cursor: pointer
     background: transparent

.activeButton
     composes: button
     border-left-color: green
     border-left-width: 2px

then use .activeButton in jsx

const MyButton = () => {
    return <button className={styles.activeButton}>select this</button>;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM