Home  >  Q&A  >  body text

React component library + SASS modularity

I started developing a React component library and wanted to reuse some SCSS code we shared with other non-React projects.

To achieve this, I tried using SASS modules in a React component.

Simple use case works fine, but I'm creating a component library and I need multiple style combinations for certain components like buttons.

Now, I have a problem with the Button component. The component is very simple, but it has 3 different variant values.

This is 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>;
};

This is 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 expected is that if I use a component like <Buttonvariant="default">I'm green</Button> there will be a green button, but what I get is Gray button.

This is an example on codesandbox

I'm stuck on this issue, can anyone help me apply different styles based on prop value?

P粉818306280P粉818306280178 days ago326

reply all(2)I'll reply

  • P粉504080992

    P粉5040809922024-03-27 20:07:46

    Please use classnames npm library.

    import cn from 'classnames';
    
    

    reply
    0
  • P粉244155277

    P粉2441552772024-03-27 19:59:53

    reply
    0
  • Cancelreply