I have a component products
which lists every product in the /Products
url. I’m trying to make another component Detail
that displays specific product
in the browser. This is the URL I’ve been trying to create Detail/{some id goes here}
. The problem is how am i going to know which product
clicked, so how am I supposed to show this specific product
in the Detail
component. I do have a Detail
and Products
component.
My router is below:
<Router> <NavbarComponent></NavbarComponent> <Switch> <Route exact path="/"> <Home /> </Route> <Route exact path="/home"> <Home /> </Route> <Route exact path="/Products"> <Products /> </Route> <Route exact path="/Detail/:int"> <Detail /> </Route> </Switch> </Router>
I’m not going to share my Products
component since It’s composed 200 lines of code. I’m just gonna share the search svg
in my Products
that I want it to take me to the Detail/{id}
page when I click.
{filtered.map((product, index) => { return ( <div key={index}> <div className="card shadow" style={{ width: "18rem" }}> <img className="card-img-top" src="https://dl.airtable.com/.attachmentThumbnails/65708b701baa3a84883ad48301624b44/2de058af" alt="Card image cap" /> <Link className="link" to={"Detail",index}> <svg stroke="currentColor" fill="white" stroke-width="0" viewBox="0 0 512 512" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path> </svg> </Link>
Advertisement
Answer
This is what you will need – https://reactrouter.com/web/example/url-params/
In summary, the :int
can be availed in the Detail
component as const {int} = useParams();
. And while handling the click in the Products
component, you will have to pass the product-id as /Details/{productId}
using the Link
component.
In this manner once the Link
is clicked to bring the route to Detail/xyz-product-id
, the Detail
component will render having that xyz-product-id
available as int
in the code.