D
D
dmitry-toster2020-12-09 15:59:00
React
dmitry-toster, 2020-12-09 15:59:00

Why nested routes don't work in react-router-dom?

It is necessary that the /productscomponent opens along the way Products. It works.
But /products/123it should display the component Product, which would have available in props what comes after products, i.e. 123. This does not work.

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <BrowserRouter>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/products">Products</Link>
          </li>
          <li>
            <Link to="/products/1">Product 1</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/" component={Home} exact />
          <Route path="/products" component={Products} />
          <Route path="/products/:slug" component={Product} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

Why is this code not working? Sandbox

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-12-09
@dmitry-toster

<Route path="/products" component={Products} />

Add here exact.
return <h1>Product# {match.slug}</h1>;

It should be here match.params.slug.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question