Pass CSS class name to component with Next.JS

Viewed 5817

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 Answers

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>
    )

};

As in ES6, this should also be available:

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