Recently I have been finding myself building larger websites that require some full-stack functionality. Rather than displaying a list of items inside a single route, I was needing to create routes for each item.

Setting up dynamic routes is actually pretty simple. Assuming you have a react app started and router installed, it is pretty simple. Suppose I have a container of articles and I have a headline listed for each one inside the container. I want to be able to click on one of those headlines and go to the page for that article.

Set up the router like this. You will notice that for our ArticlePage component we have a route that is set up like /articles/:id’ where id will be the id the article we have clicked on.

Image for post

On the container page we need to import Link.

import { Link } from ‘react-router-dom’

I am importing a bunch of article components that are displayed. These don’t show all of the article information, just enough to build interest and when any part of the component is clicked, it will redirect to the page for that article.

<Link to={/articles/${article.id}} style={{ textDecoration: ‘none’, color: “inherit” }}>

Note, that adding a style attribute is purely cosmetic, but it might be easier on your eyes.

By wrapping my component with Link, I have now made this whole component into a link to its article page.

Then, inside my ArticlePage component, in the componentDidMount function, after making a fetch request to get my articles, I use the match prop to find my article so I can render it. In case you are feeling lost at this step, know that the match prop comes with every route so this is normal.

#react #javascript #web-development #react-router #front-end-development

Dynamic Routes With React
1.50 GEEK