Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to NOT render/ hide a React component when no prop is passed?

TLDR: Cannot figure out why component is still being rendered while no props are passed.

So I have been building a NextJS application, and I have this banner component that is shown on every page of my website. It has some header text, buttons and an image:

    return (
        <div className={bannerStyles.wrapper}>
        <div className={classnames(bannerStyles.banner, "wrap", "center")}>
          <div className={bannerStyles.banner_left}>
            <h1>{props.header}</h1>
            <div className={bannerStyles.button_wrapper}>
              <div className={bannerStyles.button}>
                <Button>{props.button || null}</Button>
              </div>
              <div className={bannerStyles.button}>
                <Button>{props.scnd_button  || null}</Button>
              </div>
            </div>
          </div>
          <div className={bannerStyles.banner_right}>
            <Image src={props.image} alt=""></Image>
          </div>
        </div>
      </div>
    )
}

Inside of this, as you can see I have two Button components (The MDEast thing is an arrow icon):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Button = ({children}) => {
    return (
            <div className={buttonStyles.button}>
                <Link href="/"><a>{children} <MdEast /></a></Link>
            </div>
    )
}

Now I want the option that if no prop is passed, that the Button component(s) do(es) not render/ is hidden from the page, so that it is optional per page. Yet the Button does still render, even though I am not passing any props on my About page. My about page:

const About = () => {
    return (
        <>
            <Banner 
                header="Hello this is my code"
                image={banner_placeholder}
            />
        </>
    )
}

PS. I am fairly new to React and NextJS, so this might be a beginner mistake, or I am not understanding the fundamentals well enough, but could someone point me in the right direction please?

>Solution :

To conditionally render the button you can use:

props.button && <Button>{props.button}</Button>

When props.button is falsy, then button will not get rendered.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading