Home > Enterprise >  Passing prop to handler messes up routing
Passing prop to handler messes up routing

Time:11-22

I have a handler like so: const addToCartHandler = (id) => { navigate(`/cart/${brand}/${id}?qty=${qty}`)};

and a button component: <Button onClick={addToCartHandler} className="btn-block w-75" disabled={item.countInStock === 0} type="button">Add to Cart </Button

When I pass an ID to the addToCartHandler(someID), I get erroneously navigated directly to /cart/${brand}/${id}?qty=${qty} when I click on a link that routes to /product/:brand

When I don't pass anything and leave off the call (), I am accurately routed to the brand page.

Is there an explanation for this behavior?

CodePudding user response:

Hope this helps, more detail & examples available from ReactJS docs, https://reactjs.org/docs/faq-functions.html#how-do-i-pass-an-event-handler-like-onclick-to-a-component

How do I pass a parameter to an event handler or callback? You can use an arrow function to wrap around an event handler and pass parameters:

<button onClick={() => this.handleClick(id)} />

  • Related