Rue Vitale
Rue Vitale

Reputation: 1891

Dynamic Routing in gatsby

I am doing the following:

In pages/app.js

import React from "react"
import Layout from "../components/layout"
import { Router } from "@reach/router"
import Categories from "../components/Categories/Categories"
import BookListPage from "../components/Book/BookListPage/BookListPage"
import BookDetail from "../components/Book/BookDetail/BookDetail"
import Reader from "../components/Book/Reader/Reader"
import Author from "../components/Book/Author/Author"
import Account from "../components/Login/Account"
import InvitationLink from "../components/Promotions/Invitations/InvitationLink"
import StackSocial from "../components/Promotions/StackSocial"
import PasswordChange from "../components/Login/PasswordChange"
import AcceptInvite from "../components/Promotions/Invitations/Accept"
import SignUp from "../components/Login/SignUp"
import Login from "../components/Login/Login"
import Logout from "../components/Login/Logout"


const App = () => (
  <Layout>
    <Router>
      <Categories path="/app/categories/:id" />
      <BookListPage path="/app/category/:category" />
      <BookListPage path="/app/category/:category" />
      <BookDetail path="/app/books/:id" />
      <Author path="/app/author/:id" />
      <Reader path="/app/reader/:id" />
      <Account path="/app/account" />
      <StackSocial path="/app/stacksocial" />
      <PasswordChange path="/app/passwordchange" />
      <InvitationLink path="/app/invite" />
      <AcceptInvite path="/app/invite/accept" />
      <Logout path="/app/logout" />
      <Login path="/app/login" />
      <SignUp path="/app/signup" />
    </Router>
  </Layout>
)

export default App

In gatsby-node.js:

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions

  // page.matchPath is a special key that's used for matching pages
  // only on the client.
  if (page.path.match(/^\/app/)) {
    page.matchPath = "/app/*"

    // Update the page.
    createPage(page)
  }
}

How can change the code so that all urls get dynamically routed not just /app urls? I want to be able to create the dynamic url /books/:id not /app/books/:id

I am using GATSBY JS React Framework

Upvotes: 1

Views: 1806

Answers (1)

EliteRaceElephant
EliteRaceElephant

Reputation: 8162

Remove the app/ part:

      <Categories path="/categories/:id" />
      <BookListPage path="/category/:category" />
      <BookListPage path="/category/:category" />
      <BookDetail path="/books/:id" />
      {/* ... */}

Make it match the base URL:

// Not sure if I edited this regex correctly. 
// Might need some more tweaking. 
// You want it to match everything after the first `/`
if (page.path.match(/^)) { 
  page.matchPath = "/*"

Upvotes: 1

Related Questions