Site logo
Authors
  • avatar Nguyễn Đức Xinh
    Name
    Nguyễn Đức Xinh
    Twitter
Published on
Published on

React SearchParams

Overview

React SearchParams is a valuable feature provided by React Router, offering the useSearchParams hook for efficient management of query parameters in your React applications. <br /> This feature simplifies the process of reading and updating query string parameters, allowing developers to seamlessly handle dynamic data and enhance search functionality within their applications

Usage

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

export function Apps() {
  const [searchParams, setSearchParams] = useSearchParams()
  const search = searchParams.get('search') || ''

  const onChange = (event) => {
    const name = event.target.name
    const params = { [name]: event.target.value }
    const newSearchParams = createSearchParams(params)
    setSearchParams(newSearchParams)
  }

  return (
    <div>
        <input name="search" value={search} onChange={onChange} placeholder="search product..." />
    </div>
  )
}

Demo

<iframe src="https://codesandbox.io/embed/ducxinh-it-7jps7n?fontsize=14&hidenavigation=1&theme=dark" style={{ width: '100%', height: '500px', border: 0, borderRadius: '4px', overflow: 'hidden' }} title="ducxinh-it" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" />

Ref

https://reactrouter.com/en/main/hooks/use-search-params