user12067722
user12067722

Reputation:

Using search params with HashRouter from react-router

I find it hard to use window.location.search together with HashRouter as it always ends up like this: localhost:3000/?id=1#/person

With BrowserRouter it was no problem using window.location.search. Is there any way to make search params appear like this with HashRouter: localhost:3000/#/person?id=1

Upvotes: 4

Views: 3219

Answers (1)

Ajeet Shah
Ajeet Shah

Reputation: 19813

Search params works fine with HashRouter as you need:

Routes configuration:

const Routes = () => {
  return (
    <>
      <HashRouter>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/person?id=1">Person 1</Link>
          </li>
          <li>
            <Link to="/person?id=2">Person 2</Link>
          </li>
        </ul>

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route exact path="/person">
            <Person />
          </Route>
        </Switch>
      </HashRouter>
    </>
  )
}

Generated routes in browser when you click the links:

Home: http://localhost:3000/#/
Person 1: http://localhost:3000/#/person?id=1
Person 2: http://localhost:3000/#/person?id=2

Person component, where you can access search params:

import React from 'react'
import { useLocation } from 'react-router-dom'

function Person() {
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  return (
    <>
      <div>Person, id: {searchParams.get('id') ?? 'No ID'}</div>
    </>
  )
}

Here is a sandbox

Upvotes: 4

Related Questions