Home > Mobile >  React components library SASS modules
React components library SASS modules

Time:11-09

I'm starting to work on a react components library and I want to reuse some SCSS code we share with other non-react projects.

To accomplish that, I'm trying to use SASS modules into react component.

The simple use case works fine, but I'm creating a components library and I need to have several style combinations for some components like the button.

Right now, I'm having an issue with the Button component. Component is pretty simple, but it has 3 different variant values.

Here is the Button.tsx file:

import React from "react";
import styles from "./Button.module.scss";

type Variant = "default" | "primary" | "tertiary";

interface Props {
  children: String;
  variant: Variant;
}

export const Button: React.FC<Props> = ({ children, variant }) => {
  return <button className={`${styles.button} ${variant}`}>{children}</button>;
};

and here is the Button.module.scss file:

.button {
  border: none;
  padding: 0.5rem 1.5rem;
  border-radius: 0.25rem;
  background-color: grey;
  color: white;

  &.default {
    background-color: green;
  }
  &.primary {
    background-color: red;
  }
}

What I expect, is to have a green button if I use the component like <Button variant="default">I'm green</Button>, but instead I'm getting the grey button.

Here is a live example on codesandbox

I'm stuck on this, could somebody help me to apply different styles based on prop values?

CodePudding user response:

<button className={`${styles.button} ${styles[variant]}`}>

CodePudding user response:

Please use classnames npm library.

import cn from 'classnames';

<button className={cn(styles.button, styles[variant])}>
  • Related