How to get pathname in the layout file in gatsby

Tags: , , ,

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
          query SiteTitleQuery {
            site {
              siteMetadata {
        render={data => (
              <Provider store={store}>
Layout.propTypes = {
  children: PropTypes.node.isRequired

export default Layout.


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>

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

Source: stackoverflow