I am making a shopping page and I have products displayed. Every time a user clicks on a product, router should render the product page where all the info on the product will be.
I have my routes set up like this:
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products />}>
<Route path=":productId" element={<SelectedProduct />} />
</Route>
</Routes>
</BrowserRouter>
And inside of <Products />
I have:
return (
<div className="full-products-container">
<div className="displayed-products-container">
{productsToDisplay.map((product) => (
<Link
to={`/products/${product.id}`}
key={product.id}
className="product-box"
>
<img
src={product.image}
className="product-image-displayed"
/>
<div className="product-name">{product.name}</div>
<div className="product-price">${formatNumber(product.price)}</div>
</Link>
))}
</div>
<Outlet />
</div>
);
And now every time a product is clicked, the <SelectedProduct />
component gets rendered inside of my <Products />
component?
How do I make it that every time a product is clicked, the <SelectedProduct />
renders entirely? And not inside of it's parent?
CodePudding user response:
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:productId" element={<SelectedProduct />} />
</Routes>
</BrowserRouter>
CodePudding user response:
it's weird that you are nesting a single product page since i don't think there is any ui that you are sharing between products page and selected products page but if you want to nested routes you need to pass Outlet
component on the parent to for nested rendering.
you can look at the code below.
import {
BrowserRouter,
Routes,
Route,
Link,
useParams,
Outlet
} from "react-router-dom";
function Products() {
return (
<div>
<Link to={"/id"}>Product Link</Link>
<Outlet />
</div>
);
}
function SingleProduct() {
const { id } = useParams();
return <div>Product Id ${id}</div>;
}
function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route path="/" element={<Products />}>
<Route path=":id" element={<SingleProduct />} />
</Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
if you don't want to share the UI than just use the above solution mentioned by konrad