How to create dynamic route in gatsby

后端 未结 2 848
一整个雨季
一整个雨季 2020-12-01 18:09

I have setup gatsby project using this link. It is working correctly.

Now I know how to create route by defining the component inside the pages

相关标签:
2条回答
  • 2020-12-01 18:58

    You have to explicitly tell gatsby that a path should be dynamic. From the docs:

    // gatsby-node.js
    // Implement the Gatsby API “onCreatePage”. This is
    // called after every page is created.
    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)
      }
    }
    

    and then you can use dynamic routing in src/pages/app.js

    import { Router } from "@reach/router"
    
    const SomeSubPage = props => {
      return <div>Hi from SubPage with id: {props.id}</div>
    }
    
    const App = () => (
      <Layout>
        <Link to="/app/1">First item</Link>{" "}
        <Link to="/app/2">Second item</Link>{" "}
    
        <Router>
          // ...dynamic routes here
          <SomeSubPage path="/app/:id" />
        </Router>
      </Layout>
    )
    
    export default App
    

    Everything that goes to /app/* will be handled dynamically now. You should find your id as usual in the props.

    Have a look at their authentication example https://github.com/gatsbyjs/gatsby/tree/master/examples/simple-auth

    0 讨论(0)
  • 2020-12-01 19:10

    You can use gatsby-plugin-create-client-paths. It uses matchPath. For more info check

    1. https://www.gatsbyjs.org/docs/gatsby-internals-terminology/#matchpath
    2. https://www.gatsbyjs.org/packages/gatsby-plugin-create-client-paths/
    0 讨论(0)
提交回复
热议问题