Skip to content
Advertisement

How to get pathname in the layout file in gatsby

I am working with gasby and here the main file is always layout.js which is the parent of them all. Since it is a parent file then how can I get a location props this.props.location.pathname inside it?

Here is my layout component

class Layout extends Component {
  componentWillMount() {
    console.log(this.props, 'dssssssssssssf')
  }

  render() {
    const { children } = this.props
    return(
      <StaticQuery
        query={graphql`
          query SiteTitleQuery {
            site {
              siteMetadata {
                title
              }
            }
          }
        `}
        render={data => (
          <>
            <div>
              <Provider store={store}>
                {children}
              </Provider>
            </div>
          </>
        )}
      />
    )
  }
}
Layout.propTypes = {
  children: PropTypes.node.isRequired
}

export default Layout.

Advertisement

Answer

As stated in the Gatsby docs:

In v1, the layout component had access to history, location, and match props. In v2, only pages have access to these props; if you need these props in the layout component, pass them through from the page.

What this is means is that you need to go to where your Layout component is rendered, which will be the index.js or app.js page usually, and pass the the location props to it directly:

import React from "react"
import Layout from "../components/layout"

export default props => (
  <Layout location={props.location}>
    <div>Hello World</div>
  </Layout>
)

Then you can use it in your layout. You can also read more here.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement