Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create routes with params in gatsbyjs

I want to create a route that uses a slug as a parameter in my gatsby generated website.

I have a list of projects that sit on the route /projects/<slug>.

Usually with react router I would create a route like so:

<Route exact path='/projects/:project' component={Projects} /> 

It seems in gatsby, I have to create a new file under the ./pages directory and that creates a new route. I have a page called projects where I try do a look up on the route param but only seem to get the 404 page.

// ./pages/projects.js

class SingleProject extends Component {

  state = {
    project: {}
  }

  componentDidMount(){
    const project = this.props.projects.find(project => project.slug === this.props.match.params.project)
    this.setState({project})
  }

  render() {
    return (
      <div className="single-project" >
      </div>
    )
  }
}

export default SingleProject;

How can I have routes with parameters in gatsby?

I have just come across client only routes but I guess these routes wont be statically generated.

I will have a predefined list of slugs so perhaps there is a way to create a page for each of the project slugs? I guess I could manually create a file within ./pages/projects/<slug> foreach project I have?

like image 505
Stretch0 Avatar asked Aug 23 '18 15:08

Stretch0


People also ask

How does Gatsby create a route?

Creating Routes: To create a route in Gatsby, you can simply create a new page with a React component inside the 'src/pages' directory. It will automatically create a route for that page in your application. For this, let's create a new page name 'gfg. js' inside our pages folder.

Can we use React router in Gatsby?

So, I have this really cool tabs component on my Gatsby project that uses react-router-dom. I was blindly using it without knowing that Gatsby is no longer compatible with react-router-dom. I only found out when building the project, since in develop it works perfectly.


1 Answers

You'll want to use the createPage method that Gatsby gives you inside gatsby-node.js's createPages API. There is a guide in the Gatsby documentation that shows you can achieve exactly this. Here's an even simpler example from a similar question.

export const createPages = ({ actions }) => {
  const { createPage } = actions;

  createPage({
    path: '/projects/hello-world',
    component: SingleProject,

    // Send additional data to page component
    context: {
      id: 'hello-world',
    },
  });
};
like image 112
Fabian Schultz Avatar answered Sep 18 '22 04:09

Fabian Schultz