reactjssass

How to define className dynamically from a SCSS module in React component?


I've defined my button React component as follows:

import Styles from './styles.module.scss';
import { IButton } from './button.types';
const Button = (props: IButton) => {
    const { variant, title, size } = props;

    return (
        <>
            <button className={`${Styles.btn}}`} >
                {title}
            </button>
         
        </>
    );

}
export default Button

And my styles are defined as follows:

.btn {
    cursor: pointer;
    border: none;
    font-family: "rayan-sans-default";

    &.primary {
        color: $basic-25;
        background-color: $brand-500;

        &--xs {
            font-size: $font-size-xs;
            font-weight: $font-weight-medium;
            padding: 2px 10px;

        }

        &--sm {
            font-size: $font-size-sm;
            font-weight: $font-weight-medium;
            padding: 5px 14px;

        }

        &--md {}

        border-radius: $radius-xs;
    }


}

If my button component is used as follows:

<Button size="sm" variant="primary" title="primary"/>

How should my className be in the button.tsx component to be defined to have the current size class dynamically?


Solution

  • I think the only way to achieve this is by constructing the key based on your SCSS structure.

    let classAttributes: string[] = [Styles.btn];
    
    if (variant) classAttributes.push(Styles[`${variant}`]);
    
    if (variant && size) classAttributes.push(Styles[`${variant}--${size}`]);
    
    let classes = classAttributes.join(' ');
    return (
      <>
        <button className={classes}>{title}</button>
      </>
    );
    

    Demo @ StackBlitz