2
0

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 5 years have passed since last update.

React-Staticの基本ルーティング設定

Posted at

はじめに

プログラミング歴2ヶ月の素人が書いています。(間違っていたらご指摘ください)

「React-Staticのルーティングを設定する」ための学習メモです。

  • React-Staticのルーティング

上記についてまとめます。

👇React-Static公式👇
https://github.com/react-static/react-static

今回の目的

React-Staticで生成したブログに、ページを追加します。

基本のルーティング

static.config.js
export default {
  getRoutes: async ({ dev }) => [
    // A simple route
    {
      path: 'about',
      template: 'src/containers/About',
    },
  • path: URLに入力される文字列。ルート移行を記述します。

  • template: コンポーネントまでのパス

この2点のみで基本のルーティングは動きます。

データを渡すルーティング

//static.config.js
import axios from 'axios'

export default {
  getRoutes: async () => {
    const { data: posts } = await axios.get(
      'https://damp-thicket-88898.herokuapp.com/posts'
    )
    return [
      {
        path: 'foo',
        template: 'src/containers/Foo',
        getData: async () => ({
        posts,
      }),
  }
}

//---ここから別ファイル---
//src/containers/Foo.js

import React from 'react'
import { useRouteData } from 'react-static'

export default function Testes() {
  const { posts } = useRouteData()//渡したデータを受け取る
  return (
  <p>{posts[0]['title']}</p>//データの利用
  )
}

ルート先のコンポーネントにデータを渡す場合は、getData: async ()関数を利用します。

ルート先のコンポーネントで、const { object } = useRouteData()の形で受け取ることができます。

動的にルートを変更する場合

static.config.js
export default { //エクスポート
  getRoutes: async () => { //ブログエントリを取得し'posts'にJSONを格納
    const { data: posts } = await axios.get(
      'https://damp-thicket-88898.herokuapp.com/posts'
    )

    return [ // 各blogポストへのパスの配列を返す
      {
        path: '/blog',
        getData: () => ({
          posts, //Blogコンポーネントで使用できるようデータを渡す
        }),
        children: posts.map(post => ({ //Postsコンポーネント
          path: `/post/${post.id}`, // '/blog/post/1'みたいな各ポストへのパス
          template: 'src/containers/Post', //Postコンポーネントを元にレンダリング
          getData: () => ({
            post,// Postsコンポーネントで使用できるようデータを渡す
          }),
        })),
      },
    ]
  },

配列に合わせて、動的にルーティングを設定します。
配列内に含まれるIDを利用します。

また、その子コンポーネントで利用できるようデータをgetData: async ()関数を利用して渡します。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?