'How to retrieve the parameter after a hash (#) with React Router and useParams hook?

I have a route like

<Route path="/search/:slug"><SearchPage /></Route>

in my React Router. SearchPage is a component that uses the useParams() hook provided by react-router-dom.

// SearchPage.js
import React from 'react';
import { useParams } from 'react-router-dom';

export function SearchPage(props) {
    const { slug } = useParams();
    console.log(slug)
    // ...do other stuff
}

However, when I navigate to /search/foo#bar, the SearchPage component only receives foo in the slug. It is possible for my component to receive the full foo#bar, or, better yet, foo and bar separately?



Solution 1:[1]

In a URL like this: "/myUrl/products/product12?myQuery=12#myHash" The UseParams will return everything up to the query e.g "/myUrl/products/product12" but not the query "?myQuery=12#myHash".

React has a hook for this "useLocation". Use Location will give you an object with 4 things but only 3 that you need to worry about for this example, ( "pathname": "/myUrl/products/product12", "search": "myQuery=12", "hash": "myHash")

import { useLocation } from 'react-router-dom';
const QueryDetails = () => {
    const location = useLocation();
    const myQuery  = location.search;

return (
        <div className='container mt-2'>
           <p>{myQuery}</p>
        </div>
    );
}
 
export default QueryDetails;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter May