skip to Main Content

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 following :

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

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. See if the following code helps.
    Use the variant and size parameters as keys to access the properties of Styles.

    const Button = (props: IButton) => {
      const { variant, title, size } = props;
      const buttonSize = `${variant}--${size}`
      const buttonClass = `${Styles.btn} ${Styles[variant]} ${Styles[buttonSize]}`;
        
      return (
        <>
           <button className={buttonClass} >
              {title}
           </button>
        </>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search