0

I am using react-router-dom 6.4.2.

The expected result:

When the user browses the link http://mysite/?search=123, my website returns the search result of 123,

Here is my App.js:

<Router>
  <Routes>
    <Route exact path='/?search=:keyword' element={<SearchEng />} />
    <Route path='/' element={<Home />} />
  </Routes>
</Router>

The actual result:

Unfortunately, when a user browses the link http://mysite/?search=123, it always returns the Home component.

Would you help to fix the problem?

The KNVB
  • 3,588
  • 3
  • 29
  • 54

1 Answers1

1

it should be something like this:

in App.js

<Router>
  <Routes>
    <Route exact path='/search' element={<SearchEng />} />
    <Route path='/' element={<Home />} />
  </Routes>
</Router>

in SearchEng.js

add this line in your component. document about useSearchParams

const [searchParams] = useSearchParams();

useEffect(() => {
  const params = Object.fromEntries([...searchParams]);
  console.log(params);
}, [])

when you go to http://mysite/search?search=123, you should get { search: "123" } in console.

Layhout
  • 1,445
  • 1
  • 3
  • 16
  • Because of historical issues, the solution not 100% fit my case. However, I will try your implementation in my environment. – The KNVB Dec 19 '22 at 05:55
  • @TheKNVB i found [this code sandbox](https://codesandbox.io/s/using-usesearchparams-0neu9?file=/src/App.js) that might help. – Layhout Dec 19 '22 at 06:26