Search code examples
reactjsgatsby

Hide a image only from homepage


I am trying to hide a logo from footer, only in homepage all other pages it should be shown. I cant figure out a solution as a beginner in react please help.


Solution

  • Gatsby exposes a location property by default in top-level components (pages and templates) so in your homepage (index.js) you only need to do something like:

    const IndexPage = (props) => (
      <Layout>
        <Seo title="Home" />
        {props.location.pathname !== "/" && (
          <StaticImage
            src="../images/example.png"
            loading="eager"
            width={64}
            quality={95}
            formats={["auto", "webp", "avif"]}
            alt=""
            style={{ marginBottom: `var(--space-3)` }}
          />
        )}
      </Layout>
    );
    

    In the example above, I'm assuming the image you want to hide is a StaticImage but you can replace it with your image or whatever you want.

    The location contains a structure like:

    {
      key: 'ac3df4', // does not populate with a HashHistory!
      pathname: '/somepage',
      search: '?someurlparam=valuestring1&anotherurlparam=valuestring2',
      hash: '#about',
      state: {
        [userDefined]: true
      }
    }
    

    Source: docs

    So you can compare the pathname with the current page (props.location.pathname !== "/")

    If your footer is in a different component, you can also pass the location property into the Footer (via Layout if needed) component and apply the same approach.