共通のコンポーネント使ってて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