简体   繁体   中英

Pathname conditional rendering in React

How can I conditionally add a component to the render on certain pathname ?

Using const pathname = this.props.location.pathname I identify the current pathname

Then I get the slugs of the pages I want to identify using

const specialPages = get(this.props, 'data.allContentfulSpecialPages.edges')

I then organise the returned data by

const special = specialPages.map(({ node: page })=> (
     `/parent/${page.slug}`
))

and this returns the page slugs as

["/parent/page1", "/parent/page2", "/parent/page3", "/parent/page4", "/parent/page5", "/parent/page6"]

All seems good to now but when I try to add add

let PageHeader;
    if (pathname !== special) {
      PageHeader =
      <Header/>;
    } else {
      PageHeader = null
    }

it doesn't do remove the <Header/> for pathname identified in special

Have I not correctly defined each in the array ?

Edit - I have just noticed the issue but unsure of the fix. const special is returning as /parent/page1/parent/page2/parent/page3/parent/page4/parent/page5/parent/page6

When adding to console.log(special) I receive

0:"/parent/page1"
1:"/parent/page2"
2:"/parent/page3"
3:"/parent/page4"
4:"/parent/page5"
5:"/parent/page6"
length:6
__proto__: Array(0)

So I believe I need to map these differently.

If I'm understanding correctly, you want to conditionally add a component to the render based on pathname. A common pattern I've seen for this is to use the and operator with the condition you're looking to check and the component to render if need be. Something like this.

{{ pathname !== special && <Header/> }}

This will not display anything if the condition is not true and will display Header component if condition is true.

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