简体   繁体   中英

Conditionally render sibling component

I have a page component with several components. I only want to render the SecondaryNavigation component if there are two or more objects found in the associated data array. My structure is as follows:

<main>
  <MainNavigation>
  <Hero>
  <SecondaryNavigation>
  other stuff...
<main>

I tried creating a function that would check for the data and return the component as follows:

renderSecondaryNavigation() {
  return <div>Hecka Hopeful</div>;
}

and adding this to the return object:

<main>
  <MainNavigation>
  <Hero>
  {this.renderSecondaryNavigation}
      other stuff...
<main>

Before I even jumped into the logic I ran the code to see if it would render and I ended up with "Warning: Functions are not valid as a React child."

Is there an elegant way to do this? Thanks!

You aren't calling the function in order to get the markup returned, you are only passing in the reference to the function object

Change

{this.renderSecondaryNavigation}

To

{this.renderSecondaryNavigation()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM