skip to Main Content

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


  1. I would suggest you to do condition check on the parent component instead of the child component.

    Item page:

    function ItemPage() {
    
        return ( 
            <>
               {condition && <AddToCart />}
            </>
        );
    }
    
    export default AddToCart;
    

    Add to Card:

    import { useLocation } from 'react-router-dom';
    
    function AddToCart() {
    
        return ( 
            <span className='add-to-cart'>
              <button>Add Item</button>
              <button>Cart</button>
            </span>
        );
    }
    
    export default AddToCart;
    

    If u wanna display the add to cart on every item page.You don’t have to include the condition check.

    Login or Signup to reply.
  2. 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.

    import { useLocation } from 'react-router-dom';
    
    function AddToCart() {
       function IsItemPage() {
         const location = useLocation();
         const pathSegments = location.pathname.split('/');
    
         if (pathSegments[0] === '/item_page' && pathSegments.length > 1) {
           const itemId = pathSegments[1];
           console.log('Item ID:', itemId);
           return true;
          }
          return false;
        }
    
        return IsItemPage() && (
           <span className='add-to-cart'>
             <button>Add Item</button>
             <button>Cart</button>
           </span>
         );
     }
    
    export default AddToCart;
    
    Login or Signup to reply.
  3. 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:

    useMatch("/item_page/:id?");
    

    This will match any "/item_page" and "/item_page/XYZ" sub-route path, returning a defined PathMatch object for matches, or null for non-matches.

    Code:

    import { useMatch } from "react-router-dom";
    
    function AddToCart() {
      const isItemPage = useMatch("/item_page/:id?");
    
      return (
        isItemPage && (
          <span className="add-to-cart">
            <button>Add Item</button>
            <button>Cart</button>
          </span>
        )
      );
    }
    
    export default AddToCart;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search