0
2

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.

【Next.js】ルーティング

Last updated at Posted at 2022-11-10

ルーティングとは??

リクエストされたURLと対応する処理を関連付けること

ファイルのパスがそのままURLになります

基本的なルーティング

ディレクトリ構成は以下の通り
├─pages
│ ├─exapmle_router
│ │ └─otameshi
│ │ │ └─[number].js
│ │ │ └─Example.js
└─styles

//Example.js
const Example = () => {
  return <h1>Exampleが出力されます</h1>
}

export default Example;

URLを***http://localhost:3000/example_router/otameshi/Example***としてあげると画面に「Exampleが出力されます」と表示された
このようにファイルのパスが直接URLになっていることが確認できる

次に動的なルーティングについて確認する

otameshiフォルダの中にExample.js以外のファイルを追加していきたい場合を考える
その時に毎回Example2.js,Exapmle3.js...とファイルを追加することはしない

動的なルーティングを用いると.jsファイルを1つ準備するだけでこれを解決することができる

ファイルの名前が[number].jsとなっているので「number」の部分がダイナミックルーティングになり、その値をJavaScript内で使用することができる
コードの中身は以下の通り

//[nubmer].js
const Number = () => {
  return <h1>[number].jsが出力されています</h1>;
};

export default Number;

URLを
http://localhost:3000/example_router/otameshi/Example2

http://localhost:3000/example_router/otameshi/Example3
とすると「Example」ではなく「[number].jsが出力されています」が表示されることが分かる

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?