0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Gatsbyでロケーション情報を参照する方法

Posted at

皆さんこんにちは!

最近学校やらプライベートやらで自分の時間が取れず投稿頻度が落ちたのですが、ちゃんと合間の時間を縫って勉強しております。

さて、今日は現在学習中のGatsby.jsにて現在いるパスやURLなどのロケーション情報を参照したいと思ったので備忘録として書いていきます。

結論から言うと、めちゃめちゃ簡単です!

Reactでロケーション情報を参照するときはhistoryとかを使うと思うのですが、このようなプラグインのインストールや面倒な設定は一切行いません。

百聞は一見に如かずということで、例を見ていきましょう!

locationプロパティ#

なんとGatsby.jsにはデフォルトでロケーション情報を参照することができます

コンポーネントの引数でlocationを指定してあげましょう!

import React from "react"

const Example = ({ location }) => {
  console.log(location)

  return (
    <></>
  )
}

export default Example

そうすると以下のような情報がログに出力されます。

hash: "###############"
host: "localhost:8000"
hostname: "localhost"
href: "http://localhost:8000/example"
key: "initial"
origin: "http://localhost:8000"
pathname: "/example"
port: "8000"
protocol: "http:"
search: ""
state: null

なんて楽なんだと脱帽しました。。。

逆にこんな簡単にできていいのかと不安になりますが、余計なことは考えないようにします。

以上、「Gatsbyでロケーション情報を参照する方法」でした!

Thank you for reading

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?