I want to know how I can make my "page" variable in the below code dynamic, so I can properly compare it with the location.pathname
variable which will have dynamic page ids.
import { useLocation } from 'react-router-dom';
function AddToCart() {
function IsItemPage() {
const page = '/item_page';
const location = useLocation();
console.log(location);
if (location.pathname == page) {
return true;
};
}
return IsItemPage() && (
<span className='add-to-cart'>
<button>Add Item</button>
<button>Cart</button>
</span>
);
}
export default AddToCart;
Now each item I open from the home page has a unique id for example: "/item_page/2"
and obviously I cannot hard code it. If I provide the absolute path to the "page" variable like "/item_page/1"
or something, the component is working as expected but only for that particular item with ‘id: 1’. But I need to be able to achieve this for every item I open from the home page.
So how can I achieve this?
3
Answers
I would suggest you to do condition check on the parent component instead of the child component.
Item page:
Add to Card:
If u wanna display the add to cart on every item page.You don’t have to include the condition check.
Use useLocation hook from react-router-dom to extract the current pathname and dynamically check if it matches the expected pattern for an item page.
If you just want to check if the current URL path matches a specific path (or pattern) then you can use the useMatch hook, no need to re-invent the wheel.
Example:
This will match any
"/item_page"
and"/item_page/XYZ"
sub-route path, returning a definedPathMatch
object for matches, ornull
for non-matches.Code: