Search code examples
javascriptcssreactjsnext.jscss-modules

passing props as classNames in next.js


I am trying to have the header of each of my app's pages change color based on the current page. How I am trying to achieve this:

<Header className="headerBitcoin"></Header>

What I want is the be able to have the header component present on all 4 pages, and then just change the className to another prop to change the background but not anything else.
And the header component itself

import styles from "../../styles/Home.module.css";
export default function Header(props) {
  return (
    <div >
      <div className={props.className}>aaaaa</div>
      <div className={styles.row}>
        <div className={styles.tab}>a</div>
        <div className={styles.tab}>a</div>
        <div className={styles.tab}>a</div>
        <div className={styles.tab}>a</div>
      </div>{" "}
    </div>
  );
}

At the moment the styles for the tabs and row are working but the header is not getting its style applied.
I checked the console and found the header is getting the className headerBitcoin passed to it, however the row beneath it has the className of "Home_row__88lPM"
This is my first time working with next.js, and I know I am doing something wrong because this works in React. Any help would be appreciated.


Solution

  • I assume it's not being applied because you have the headerBitcoin styles defined in your CSS module.

    If you want to apply a class that way (className="headerBitcoin"), you need to define the class in your global CSS instead.

    If you meant to use the headerBitcoin defined in Home.module.css, then you'll want to change the className to use the scoped styles.

    import styles from "../../styles/Home.module.css";
    
    export default function Header(props) {
      return (
        <div >
          <div className={styles[props.className]}>aaaaa</div>
          // ...
        </div>
      );
    }