본문 바로가기

Frontend/React

React Hooks - UseParams / UseSearchParams (React Router DOM)

반응형

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

 

React

React is the most papular framework followed by Angular and Vue. React, like Angular uses components to build an application. However, React does not come with native features like Angular. Instead, it uses other libraries which makes React compact and sma

jin-co.tistory.com

Router Set Up

 

React Library - React Router DOM

React, by nature, does not have routring feature. React Router DOM is one of the package of the React library and, with this, we can easily create routing between pages. Let's see how we can use this library. Project Set Up Creating a React Project React R

jin-co.tistory.com

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

 

Traversy Media - YouTube

 

Traversy Media

Traversy Media features the best online web development and programming tutorials for all of the latest web technologies from the building blocks of HTML, CSS & JavaScript to frontend frameworks like React and Vue to backend technologies like Node.js, Pyth

www.youtube.com

 

728x90
반응형