Hide / Show element based on ULR Gatsby React

Viewed 320

I want to show / hide a P tag in the footer based on the url it is in.

I did it in development mode and it worked:

{acf2.texto_2_rodape_coluna_2.length > 0  && window.location.href.indexOf("mydomain")? (
              <>
                <p className="contact">
                <HiCursorClick/> <Link to={acf2.link_call_1} style={{ fontWeight: '600' }}>
                    {acf2.texto_2_rodape_coluna_2}
                  </Link>
                </p>
              </>
            ) : null}

            {acf2.texto_3_rodape_coluna_2.length > 0 && !window.location.href.indexOf("mydomain/")? (
              <p className="contact">
              <AiTwotoneVideoCamera/> <Link to={acf2.link_to_action_2} style={{ fontWeight: '600' }}>
                  {acf2.texto_3_rodape_coluna_2}
                </Link>
              </p>
            ) : null}

In development mode it works, but when I send to netlify this error occurs:

error: "window" is not available during server side rendering.

WebpackError: ReferenceError: window is not defined

1 Answers

First of all, you are using window object in the server-side (SSR) where is not allowed since gatsby develop occurs on the browser-side but gatsby build (also Netlify deploy) occurs in the server where there global objects such as window or document are not defined yet (for obvious reasons).

In Gatsby, because it extends from the @reach/router (from React) you can access a prop named location (only available in pages but you can pass downside to any children) with all the desired information without accessing the global objects. In your case:

{acf2.texto_2_rodape_coluna_2.length > 0  && location.pathname.includes('mydomain')? (
              <>
                <p className="contact">
                <HiCursorClick/> <Link to={acf2.link_call_1} style={{ fontWeight: '600' }}>
                    {acf2.texto_2_rodape_coluna_2}
                  </Link>
                </p>
              </>
            ) : null}

            {acf2.texto_3_rodape_coluna_2.length > 0 && !location.pathname.includes('mydomain')? (
              <p className="contact">
              <AiTwotoneVideoCamera/> <Link to={acf2.link_to_action_2} style={{ fontWeight: '600' }}>
                  {acf2.texto_3_rodape_coluna_2}
                </Link>
              </p>
            ) : null}

If you want to use your initial approach, you need to ensure that the window is defined as the documentation suggest by using:

if (typeof window !== `undefined`) {
  //your statement
}

Applied to your code:

{typeof window !== 'undefined' && acf2.texto_2_rodape_coluna_2.length > 0  && window.location.href.indexOf("mydomain")? (...)

Of course, it's not recommended since you have a native approach using location, and because chaining ternary conditions is not the best option in terms of code readability.

Related