It is common to use URLs to send additional information such as the id of an item. React Router DOM is one of the React libraries that makes working with routings easy. Today we will see how we can use its hooks to add a parameter or queries and get the value from them.
Project Set Up
Creating a React Project
Router Set Up
Use Param
Parameter Set Up
In the 'Route' tag add parameters using the characters below (We can add multiple parameters)
/:<parameterName>
Getting the Parameter Value
Go to the component on that path and import the 'useParams' hook and initialize
import { useParams } from 'react-router-dom'
const param = useParams()
To get the value, use the name you added on the 'path' attribute after as shown below
param.<parameterName>
Use Search Params
The additional information we add to the URL is called queries. A Querie has a key and a value and we can add multiple queries to a URL. They are separated either by '?' or '&'. We use '?' for the first query and every other query that comes after is separated by '&'
Query Set Up
For example, when we are sending name and location under this route
We add the queries to a link in the component
<Link to={'/contact?listingName=name&listingLocation=location'}>Go</Link>
Getting Values from a Query
we use useSearchParams hook to get a value from a query
Import the hook in the destination component
import { useSearchParams } from 'react-router-dom'
Initialize the hook with a value and setter as we do with the useState
const [searchParams, setSearchParams] = useSearchParams()
Use the function below with the key as a parameter to get the value
searchParams.get('listingName')
In this writing, we have seen how we can use the React router DOM' hook, 'useParams', to add parameters to a URL
References
'Frontend > React' 카테고리의 다른 글
Hooks - useContext(Global State) (0) | 2023.05.15 |
---|---|
React Hook - Redirection (React Router DOM) (0) | 2023.05.03 |
React Library - React Router DOM (0) | 2023.05.02 |
React Library - Framer Motion (0) | 2023.05.01 |
Hooks - State Management (useState, useReducer) (0) | 2023.04.19 |