はじめに
今回は"Create Dynamic Pages"を進めていきましょう!
また、今回は簡単なブログアプリを作成していくのが目的なので、かなり面白くできると思うので楽しみにしていてください!
投稿のリストを追加する
また、いつも通り新しくアプリをダウンロードせずに前回の続きを利用していきたいと思います。
最初にpageフォルダ内のindex.jsの中身を書き換えていきましょう。
import Layout from '../components/MyLayout.js'
import Link from 'next/link'
const PostLink = (props) => (
<li>
<Link href={`/post?title=${props.title}`}>
<a>{props.title}</a>
</Link>
</li>
)
export default () => (
<Layout>
<h1>My Blog</h1>
<ul>
<PostLink title="Hello Next.js"/>
<PostLink title="Learn Next.js is awesome"/>
<PostLink title="Deploy apps with Zeit"/>
</ul>
</Layout>
)また、hrefの中身において、「`」(@+Shift)という記号を使います。
「’」ではないことに注意してください。
そしてローカルホストを見ると、


クエリ文字列を介したデータの受け渡し
上記のindex.jsで何をしているか簡単に説明をしたいと思います。
これはクエリ文字列パラメータ(クエリパラメータ)を介してデータを渡しています。
この例においては“ title”クエリパラメータを渡していることになります。
「投稿」ページを作成する
pagesフォルダにpost.jsを作成し、中身を書いていきます。
import {withRouter} from 'next/router'
import Layout from '../components/MyLayout.js'
const Page = withRouter((props) => (
<Layout>
<h1>{props.router.query.title}</h1>
<p>This is the blog post content.</p>
</Layout>
))
export default Page
withRouterの細かい説明はこちらの”Routing”を参照してください。
https://nextjs.org/docs#routing
また、このように書き換えても同じ結果を得られます。
import {withRouter} from 'next/router'
import Layout from '../components/MyLayout.js'
const Content = withRouter((props) => (
<div>
<h1>{props.router.query.title}</h1>
<p>This is the blog post content.</p>
</div>
))
const Page = (props) => (
<Layout>
<Content />
</Layout>
)
export default Page
さいごに
これで"Create Dynamic Pages"は終わりです!
最後の方はやや難しく、自分もちゃんと理解できているかわかりません。
ただいつでも復習はできるので、突き進みましょう。