Gergő Horváth
Gergő Horváth

Reputation: 3705

React router Link doesn't redirect

Please see sandbox.

I'm having this code:

    <Router history={createBrowserHistory()}>
      <Switch>
        <Route path="/items/:itemId">
          <Item />
        </Route>
        <Route exact path="/items">
          <Items />
        </Route>
        <Redirect to="/items" />
      </Switch>
    </Router>

Expecting /items to be default route. Items is loading links for available items:

  const { url } = useRouteMatch();

  return (
    <div>
      <h1>Items</h1>
      {items.map((item) => (
        <Link to={`${url}/${item}`}>{item}</Link>
      ))}
    </div>
  );

Once an item link is clicked, I'm expecting the url to have the item in it, and to render Item. url is /items, so everything should work out for Switch to render:

        <Route path="/items/:itemId">
          <Item />
        </Route>

However, it's staying at /items, and not even rendering Items component anymore. No error is shown. Any idea why this is happening?

Upvotes: 0

Views: 756

Answers (2)

Utsav
Utsav

Reputation: 11

That because when it reaches the /items/:itemId Page the component get redirect back to /items , So the solution to this is just remove the redirect component

  <Switch>
    <Route path="/items/:itemId">
      <Item />
    </Route>
    <Route exact path="/items">
      <Items />
    </Route>
  </Switch>

Also there few other mistake which i saw in your code.In Item.jsx , your using

  const { item } = useParams();

This isn't going to the render the anything since it is undefined , that is because your are passing the /:itemId in Route. So try this instead

  const { itemId:item } = useParams();

here we are renaming the itemId to item inorder to accessable down in the code.

Upvotes: 1

Louay Al-osh
Louay Al-osh

Reputation: 3405

For router you are missing an exact props which is really important for your case

<Route exact path="/items/:itemId" />

and inside your Item component you misspelled the param name, because in router it's itemId where the component has a different one item, so fixing it will make the param accessible(they should be exact match)

export const Item = () => {
  const { itemId } = useParams();

  return (
    <div>
      <h1>Item</h1>
      {itemId}
    </div>
  );
};

Upvotes: 1

Related Questions