Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic route in gatsby

Tags:

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 folder. But now I have a new challenge I need to create one dynamic route so that I can pass my id in it (Just like reactjs).

<Route path: "/path/:id"/> 

How do I do that in gatsby?

like image 680
Profer Avatar asked Apr 19 '19 05:04

Profer


People also ask

What is reach router?

Reach Router is a small, simple router for React that borrows from React Router, Ember, and Preact Router. Reach Router has a small footprint, supports only simple route patterns by design, and has strong (but experimental) accessibility features.


2 Answers

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

like image 64
wiesson Avatar answered Oct 17 '22 06:10

wiesson


You can use square brackets ([ ]) in the file path to mark any dynamic segments of the URL. For example, in order to edit a user, you might want a route like /user/:id to fetch the data for whatever id is passed into the URL.

src/pages/users/[id].js will generate a route like /users/:id src/pages/users/[id]/group/[groupId].js will generate a route like /users/:id/group/:groupId

Reference: https://www.gatsbyjs.com/docs/reference/routing/file-system-route-api#creating-client-only-routes

like image 32
Adeyemi Simeon Avatar answered Oct 17 '22 07:10

Adeyemi Simeon