How to create routes with params in gatsbyjs

∥☆過路亽.° 提交于 2019-12-22 05:03:37

问题


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?


回答1:


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',
    },
  });
};


来源:https://stackoverflow.com/questions/51988998/how-to-create-routes-with-params-in-gatsbyjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!