When I console.log qty
(in the code below), I see No routes matched location "/cart"
(from browser console) instead of value of qty
. In react-router-dom v5 everything works well by passing location as props to the component, but that isn't working in v6. The following block of code work in router-dom v5:
export function CartScreen({ match, location, history}) {
const qty = location.search ? Number(location.search.split("=")[1]): 1
console.log('qty:', qty)
return (
<div>
<h1>Add to CART</h1>
</div>
)
}
Add to Cart Handler:
const addToCartHandler = () =>{
history(`/cart/${match.id}?qty=${qty}`)
}
<Button type='button' onClick={addToCartHandler} > Add To Cart </Button>
However, the above code is no valid in router-dom v6, so I try to achieve the same result by changing it to the one below(but it is not working):
const CartScreen = () => {
const match = useParams()
const location = useLocation();
const productID = match.id
const qty = location.search ? Number(location.search.split("=")[1]): 1
console.log('qty:', qty)
return (
<div>
<h1>Add to CART</h1>
</div>
)
}
App.js
function App() {
return (
<Router>
<Routes>
<Route path='/cart/:id?' element={<CartScreen/>} />
</Routes>
</Router>
);
}
export default App;
The main issue that is with the the way I used location
in router dom v 6.