DEV Community

Rafael Borges
Rafael Borges

Posted on

How set, get and delete URL Params using React

Setting the URL Params:

import { useSearchParams } from 'react-router-dom'

//startar the variable params
const [searchParams, setSearchParams] = useSearchParams()

setSearchParams((state) => {
  state.set('order', '123')

  return state
})
Enter fullscreen mode Exit fullscreen mode

Geting URL Params:

Accessing the route: http://localhost:5173/dashboard?order=123

We get this param like at example bellow:

import { useSearchParams } from 'react-router-dom'

//startar the variable params
const [searchParams, setSearchParams] = useSearchParams()

//Get the param defined
const orderId = searchParams.get('order')
Enter fullscreen mode Exit fullscreen mode

Deleting URL Params:

import { useSearchParams } from 'react-router-dom'

//startar the variable params
const [searchParams, setSearchParams] = useSearchParams()

//Delete the param order
setSearchParams((state) => {
  state.delete('order')

  return state
})
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
floatrx profile image
Andrew F.

i prefer use nuqs

Collapse
 
rafaelborges26 profile image
Rafael Borges

an another good option too