I use useLocation to get data from url, first time it worked fine. But when I reload page, string search of location will contain encode string.
Is this what the useLocation hook does?
import React from 'react';
import { BrowserRouter as Router, Route, Link, Switch, useHistory, useLocation } from 'react-router-dom';
function Home() {
const history = useHistory();
const handleSearch = () => {
history.push('/search?q=test 123');
};
return (
<div>
<button onClick={handleSearch}>Search "test 123"</button>
</div>
);
}
function SearchResults() {
const location = useLocation();
console.log(location);
const search = location.search;
const queryParams = new URLSearchParams(search);
const query = queryParams.get('q');
return (
<div>
<h2>Search Results</h2>
<p>Displaying search results for: {query}</p>
</div>
);
}
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/search?q=react test">Search</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/search" component={SearchResults} />
</Switch>
</div>
</Router>
);
}
export default App;
I want to know what’s going on here, why is it like that.