Search code examples
reactjsreact-router-dom

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

  • You need to use useLocation hook and get the hash from there. First step is to import useLocation from react-router-dom:

    import useLocation from "react-router-dom";
    

    Inside the component function, use this:

    const { hash } = useLocation();
    

    From the docs:

    useLocation

    The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes.

    This could be really useful e.g. in a situation where you would like to trigger a new “page view” event using your web analytics tool whenever a new page loads