Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current url in Gatsby?

Tags:

gatsby

I am currently creating share buttons with Gatsby and would like to share content based on the current url, which changes depending on the environment and the current page. With GoHugo this can be called with {{ .Permalink }}. Does anyone know how to do this with Gatsby?

I have a ShareButtons component, which is a child of BlogPostTemplate.

like image 260
David Avatar asked Sep 01 '25 18:09

David


2 Answers

You can get the current url using the location prop from the @reach/router Location component.

import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Location } from '@reach/router';

class SomeComponent extends Component {
  static propTypes = {
    location: PropTypes.object.isRequired
  }

  render() {
    const { location } = this.props;
    return <div>{JSON.stringify(location)}</div>;
  }
}

export default props => (
  <Location>
    {locationProps => <SomeComponent {...locationProps} {...props} />}
  </Location>
);
like image 180
Clay Risser Avatar answered Sep 06 '25 22:09

Clay Risser


Gatsby uses react-router behind the scene meaning location information is available in props. This information can be used in a conditional statement or passed into styled-components like so:

<Component isIndex={this.props.location.pathname === '/'}>

like image 39
fstep Avatar answered Sep 06 '25 23:09

fstep