skip to Main Content

I am using NextJS and I have a route called about(It’s contents is displayed via page.js). Inside /about/page.js, I am showing a component called <Hero /> and I want to pass a prop to <Hero heroHeight={'height: 400px'} /> to my CSS module for styling purposes.

Hero.js

'use client';

import styles from '../page.module.css';
import style from './Hero.module.css';

const Hero = ({ heroHeight }) => {
  return (
    <div className={`${styles.pageWidth} ${style[heroHeight.updateTheHeight]`}>

    </div>
  );
};

export default Hero;

Hero.module.css

.updateTheHeight{
  border: 1px solid green;
  /* I want to pass the prop here which is height: 400px */
}

The code above is currently not working. I want to pass the value of the prop which is height: 400px to .updateTheHeight class.

Do you know what is the problem in my code? Any help is greatly appreciated. Thanks!

2

Answers


  1. , the issue with your code is that you’re trying to mix CSS modules and dynamic styles, but CSS modules don’t really work that way. They’re more for static, predefined class names. But no worries, there’s a simple fix.

    You can just use inline styles for dynamic stuff. Inline styles let you plug in your JavaScript values directly into your style attribute.

    Here’s what you can do:

    In your Hero.js, instead of trying to attach your prop to a CSS module class, you can directly use it in a style object. Something like this:

    const Hero = ({ heroHeight }) => {
     const dynamicStyle = {
     height: heroHeight, // This is where your dynamic height goes
     border: '1px solid green', // Assuming you always want this green border
    };
    
     return (
      <div className={styles.pageWidth} style={dynamicStyle}>
       {/* Your Hero content */}
      </div>
     );
    };
    

    When you use your Hero component, just pass the height like you were doing:

    <Hero heroHeight="400px" />
    
    Login or Signup to reply.
  2. You can’t really pass values to css files. There are two ways you can do this.

    You can however use the style attribute to pass the height dynamically.

    'use client';
    
    import styles from '../page.module.css';
    import style from './Hero.module.css';
    
    const Hero = ({ heroHeight }) => {
     return (
       <div className={`${styles.pageWidth} ${style[heroHeight.updateTheHeight]`} style={heroHeight}>
    
       </div>
     );
    };
    
    export default Hero;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search