'ReactJS No routes matched location because of question mark in query string

Hello I have a react app with this route, I use react-router-dom.

<Route path='/contacts?page=:page' element={} />

And I navigate like that:

navigate(/contacts?page=${newPage});

but because of question mark, in the console appears "No routes matched location", when I change the question mark with other symbol for example _ everything is fine.

Do you know how to resolve this problem?



Solution 1:[1]

There is a couple of solutions for this

Solution 1

You could try with parameters like this

<Route path="/contacts/page/:page" component={} />

And navigate like this

navigate(/contacts/page/${newPage});

Solution 2

If you want to work with query strings, with question mark you dont have to mention it in your simply add the query string (?page) and access it later like I did in this example

Example

<Route path='/contacts' element={} />

Navigate between pages the same way

navigate(/contacts?page=${newPage});

But you will have to access the page query string like this

import {useLocation} from "react-router-dom";
const location = useLocation();
console.log(location);
  return (
    <div>
      <h1>Page</h1>
      <p>{new URLSearchParams(location.search).get('page')}</p>
    </div>

Hopefully this helps, but I'd recomend to go with the first solution

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1