Sometimes, we want to get query parameters from a hash fragment with React Router v5.
In this article, we’ll look at how to get query parameters from a hash fragment with React Router v5.
Get Query Parameters from a Hash Fragment with React Router v5
To get query parameters from a hash fragment with React Router v5, we can use the useLocation
hook to return the location
object and use the location.hash
property to get the hash part of the URL.
For instance, we write:
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useLocation
} from "react-router-dom";
const Foo = () => {
const location = useLocation();
const params = new URLSearchParams(location.hash);
return <div>foo {JSON.stringify([...params.entries()])}</div>;
};
const Bar = () => {
return <div>bar</div>;
};
export default function App() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/foo#/?a=1&b=2">foo</Link>
</li>
<li>
<Link to="/bar">bar</Link>
</li>
</ul>
<Switch>
<Route path="/foo" children={<Foo />} />
<Route path="/bar" children={<Bar />} />
</Switch>
</div>
</Router>
);
}
We have the Foo
component that calls the useLocation
and assign the returned object to the location
variable.
Then we get the hash part of the URL with the location.hash
property.
Next, we parse the hash part of the URL into an object with the URLSearchParams
constructor.
And then we get the entries from the parsed query string with the entries
method.
In App
, we define some Route
s that map URLs to the components we defined.
And we add Link
s with the to
prop set to a URL with the hash part in it in the first link.
Then when we click the first link, we see the array with the parsed query string from the hash part of the URL.
We should see:
foo [["#/?a","1"],["b","2"]]
displayed when we click foo.
Conclusion
To get query parameters from a hash fragment with React Router v5, we can use the useLocation
hook to return the location
object and use the location.hash
property to get the hash part of the URL.