LoginSignup
22
7

More than 3 years have passed since last update.

next.jsでurl pathを取得したい

Last updated at Posted at 2020-10-22

共通のコンポーネント使っててpath別で処理したいときあるよね。
必要な度にググってるのでメモ。

だめな例

SSRされたときはdocumentがないので下記ではだめ。

pages/my-component.js
import React from 'react';

const MyComponent = props => {
  console.log(document.location);
...
Server Error
ReferenceError: document is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

だめな例2

client sideで使えって怒られた

pages/my-component.js
import React from 'react';
import Router from 'next/router';

const MyComponent = props => {
  console.log(Router.pathname);
...
Server Error
Error: No router instance found.
You should only use "next/router" inside the client side of your app.

いい例

hookが提供されてるからこれ使おう

pages/my-component.js
import React from 'react';
import { useRouter } from 'next/router';

const MyComponent = props => {
  const router = useRouter();
  console.log(router.pathname); // '/example/mycomponent'
...

参考

next/router | Next.js - https://nextjs.org/docs/api-reference/next/router

22
7
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
22
7