[英]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.我正在 Gatsby 上建立一个网站,我希望能够根据我所在的页面有条件地呈现一个组件。 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" 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!
非常感谢您的先进!
On any Gatsby page component you should have a location
prop.在任何 Gatsby 页面组件上,您都应该有一个
location
属性。 Then you can get the pathname using props.location.pathname
.然后你可以使用
props.location.pathname
获取路径名。 Pretty sure this should work on server-side-rendering (your build) as well.很确定这也适用于服务器端渲染(您的构建)。
The simplest and easiest (the cleanest) way to achieve it is to use the built-in props
provided by Gatsby.实现它的最简单和最简单(最干净)的方法是使用 Gatsby 提供的内置
props
。 As you can see in their documentation , it exposes a location
prop
which contains all the information needed.正如您在他们的文档中所见,它公开了一个
location
prop
,其中包含所有需要的信息。 Of course, because it's not a global browser object, such as window
or document
, it will be available during the server-side rendering as well as during the runtime.当然,因为它不是一个全局的浏览器对象,比如
window
或document
,它在服务器端渲染期间以及运行时期间都是可用的。
You can simply:您可以简单地:
import React from "react"
import { graphql } from "gatsby"
const Component = ({ location, data }) => {
return location.pathname !== 'ourcontent' ? <MyComponent /> : null
}
export default Component
You can improve it by removing the ternary condition with location.pathname !== 'ourcontent' && <MyComponent />
, is not needed to return a null
.您可以通过使用
location.pathname !== 'ourcontent' && <MyComponent />
删除三元条件来改进它,不需要返回null
。
You can also use @reach/router
.您也可以使用
@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.此代码和框显示了
@reach/router
和location.pathname
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.