LoginSignup
6

More than 5 years have passed since last update.

nextjsのルーティングまとめ

Posted at

はじめに

nextjsのroutingのREADMEに書いてあることをベースに遷移先のgetInitialPropsで取得できる内容をまとめてます

遷移後のページでは以下のコードでpath情報周りを取得してます

import React from 'react';

export default class extends React.Component {
  static async getInitialProps({ pathname, query, asPath }) {
    return { pathname, query, asPath };
  }

  render() {
    return (
      <ul>
        <li>pathname: {this.props.pathname}</li>
        <li>query: {JSON.stringify(this.props.query)}</li>
        <li>asPath: {this.props.asPath}</li>
      </ul>
    );
  }
}

ベーシックなやつ

<Link>にhrefに遷移先のurlを指定します

index.jsx
import React from 'react';
import Link from 'next/link';

export default () => (
  <Link href='/general'>
    <a>general</a>
  </Link>
);
pathname: /general
query: {}
asPath: /general

しっかりとpathの情報が取得できてます
いまはpathnameとasPathは一緒ですが、この後で違いが出てきます

クエリパラメーター付き

見たまんまですが、pathnameにpathをqueryにオブジェクトを渡します
以下が生成後のpath
/withQuery?hoge=fuga

index.jsx
import React from 'react';
import Link from 'next/link';

export default () => (
  <Link href={{ pathname: '/withQuery', query: { hoge: 'fuga' } }}>
    <a>withQuery</a>
  </Link>
);
pathname: /withQuery
query: {"hoge":"fuga"}
asPath: /withQuery?hoge=fuga

queryでしっかりと取得できてます
pathnameとasPathの違いはクエリパラメーターが付いてるかどうかでした

ファイル名そのまま、pathを変えたい場合

nextjsはpages/配下のファイル名を元にルーティングしてくれますが、urlで表示されるpathは別名がいいときはasを使います

以下のやつのurlのpathは/dummyになります

index.jsx
import React from 'react';
import Link from 'next/link';

export default () => (
  <Link href='/general' as='dummy'>
    <a>general</a>
  </Link>
);
pathname: /general
query: {}
asPath: /dummy

pathnamehrefに指定したもの、asPathasに指定したものが取得できます

おわりに

※追記していくと思います

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
6