Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally render a component in Gatsby based on specific page?

I'm building a website on Gatsby and I will like to be able to render a component conditionally based on which page I am. For example, in the footer I have a component that I don't want it to appear on the "ourcontent" page but yes for the rest of the site.

I tried doing this, which worked, however after running build gives me an error saying: "window" is not available during server side rendering.

{ window.location.pathname !== '/ourcontent'
  ? <MyComponent />
  : null
}

Im working using a Functional Component.

How would I be able to achieve this? Any help will be extremely appreciated! Thank you very much in advanced!

like image 483
user3246722 Avatar asked Nov 24 '25 10:11

user3246722


1 Answers

You can also use @reach/router. Here is an ultra simple example.

import { Location } from '@reach/router'


const IndexPage = () => (
  <Layout>
    <h1>Hi people</h1>
    <Location>
      {({ location }) => {
        console.log(location)
        if (location === '/') return <p>You are on the homepage {location.pathname}</p>
        return <h1> you are not on the homepage </h1>
      }}
    </Location>
  </Layout>
)

export default IndexPage

This codesandbox shows both the @reach/router and the location.pathname implmentations.

like image 174
apena Avatar answered Nov 26 '25 22:11

apena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!