1

I'm fetching news articles from The Guardian API. Article id's are like this: "world/live/2020/dec/31/coronavirus-covid-live-news-updates-vaccine-lockdown"

I need to go from article summary to article details and I'm using React Router for this. If I use const { id } = useParams(); and console log it, it gets only gets "world" form the id. How can I get the full id?

<Route path="/:id" component={ArticlePage} />

    {topStories.map((story) => (
      <Link to={`/${story.id}`}>
        <ImageCard key={story.id} story={story} />
      </Link>
    ))}
  • Please update your question to include a [Minimal, Complete, and Reproducible](https://stackoverflow.com/help/minimal-reproducible-example) code example. Can we see how you've defined your routes and also how you construct your links to them? – Drew Reese Dec 31 '20 at 23:40
  • Does this answer your question? [Allow slashes in route parameter on React](https://stackoverflow.com/questions/56133182/allow-slashes-in-route-parameter-on-react) – Dennis Martinez Dec 31 '20 at 23:50

1 Answers1

2

Issue

Path "/:id" will only match the first path "segment", i.e. "world" from "world/live/2020/dec/31/coronavirus-covid-live-news-updates-vaccine-lockdown".

Solution

If the path is "world/live/2020/dec/31/coronavirus-covid-live-news-updates-vaccine-lockdown" and you are trying to get coronavirus-covid-live-news-updates-vaccine-lockdown as the id then you need to define a route path that matches what you want to extract.

Something like

<Route path="/world/live/:year/:month/:day/:id" component={ArticlePage} />

Now using the params you can extract any of these, including the id.

const { day, id, month, year } = useParams();
Drew Reese
  • 165,259
  • 14
  • 153
  • 181