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?
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.
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.
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',
},
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With