2

I'm new to NextJS and currently converting a plain ReactJS project.

One thing I don't really get yet is how to properly use CSS.

I have a Button component that takes a standard class plus dynamic class names from the parent component. As you can see the class names are being passed through the prop button class - how do I properly process these class names? Currently it says undefined.

<Button buttonClass={"primary__button hero-button"}>Jetzt loslegen</Button>


import React from "react";
import style from "./button.module.scss";

export const Button = ({children, buttonClass, onClick}) => {

    return (
        <button className={style.basic__button + " " + style[buttonClass]} onClick={onClick}>{children}</button>
    )

};
2
  • can you share your button.module.scss? It seems like you are passing buttonClass primary__button hero-button to component, do you have such className? Commented Nov 2, 2020 at 10:18
  • @Shyam Yes they are inside of this scss file Commented Nov 2, 2020 at 10:19

2 Answers 2

1

The provided buttonClass prop can be multiple classNames. You have to be able to handle that.

Here's an example of how to parse this.

export const Button = ({children, onClick, buttonClass = ''}) => {

  const css = buttonClass
    .trim()
    .split(' ')
    .map((c) => styles[c]).join(' ')

    return (
        <button 
          className={`${style.basic__button ${css}`} 
          onClick={onClick}>
            {children}
        </button>
    )

};
Sign up to request clarification or add additional context in comments.

Comments

0

As in ES6, this should also be available:

<button className={classnames(styles.basic__button, css)} onClick={onClick}>{children}</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.