Params
useParams
useParams
access parameters in the URL.
// <Route path="/projects/:projectId" component={ProjectDetails} /> import { useParams } from 'react-router-dom'; const ProjectDetails = () => { const { projectId } = useParams(); return <div>Project ID: {projectId}</div>; };
useLocation
useLocation
extracts location object which provides information about the current URL.
- holds attributes like query parameter or path name.
import { useLocation } from 'react-router-dom'; const CurrentPath = () => { const location = useLocation(); return <div>Current Path: {location.pathname}</div>; };
useParams
useParams
returns an object of key/value pairs of URL parameters.
Use it to access match.params
of the current <Route>
.
import React from "react"; import { BrowserRouter as Router, Switch, Route, useParams } from "react-router-dom"; function BlogPost() { let { slug } = useParams(); return ( <div>Now showing post: {slug}</div> ); } ReactDOM.render( <Router> <Switch> <Route exact path="/"> <HomePage /> </Route> <Route path="/blog/:slug"> <BlogPost /> </Route> </Switch> </Router>, node );
useSearchParams
useSearchParams
specifically created to work with query parameters in the URL.
import { useSearchParams } from 'react-router-dom'; const QueryParamsExample = () => { const searchParams = useSearchParams(); const queryParamValue = searchParams.get('paramName'); return <div>Query Parameter Value: {queryParamValue}</div>; };
Suspense
When using SSR framework like NextJS, useSearchParams
should be wrapped with Suspense
.
import { useSearchParams } from 'react-router-dom'; import { Suspense } from 'react'; const QueryParamsExample = () => { const searchParams = useSearchParams(); const queryParamValue = searchParams.get('paramName'); return ( <Suspense fallback={<div>Loading...</div>}> <div>Query Parameter Value: {queryParamValue}</div> </Suspense> ); };
Reading the search parameter without Suspense
will attempt client side rendering of entire page which could lead to blank page until Javascript is loaded.
Suspense
lets you display a fallback until its children have finished loading.
<Suspense fallback={<Loading />}> <SomeComponent /> </Suspense>
Writing to the query string
useSearchParams
returns a URLSearchParams
object, which can be used to read and write to the query string of the current URL
const location = useLocation(); const params = useSearchParams(location.search); // Get a single value const name = params.get("name"); // Set a single value params.set("name", "John"); // Get all values const allNames = params.getAll("name"); // Delete a single value params.delete("name");
You HAVE to use .get()
or .set()
to read or write to the query string.
If you don't use the .get()
method, you will receive an object instead of a string value like {size:2}
.
const location = useLocation(); const params = useSearchParams(location.search); // what you want const val1 = params.get("field_name"); // "value" // not what you want const val2 = params; // {size: 1}
Pushing the state
back to the URL as a query string
Useful for pagination default values.
- renders with default values
- user can change the values and click a button to push the new values back to the URL as a query string which will upsert the state from URL query string
// use React Router history/location const history = useHistory(); const location = useLocation(); // using window const history = window.history; const location = window.location; useEffect(() => { // get the current URL query string const params = new URLSearchParams(location.search); // get the value of the updated field_name query string const value = params.get("field_name"); // if the value is not found if(!value) { // set the state to default value setNewValue(defaultValue); // set the default value to the query string params.set("field_name", defaultValue.field_name); // set another value to the query string params.set("field_name_2", defaultValue.field_name_2); } }, [window.location.search]) const newSearchParams = new URLSearchParams(window.location.search); // sets new Url query string newSearchParams.set("field_name", newValue.toString()); // set new value to the state setNewValue(newValue); // pushes new Url query string using React router history history.push( { pathname: window.location.pathname, search: newSearchParams.toString() } )