Home > Software design >  React Router - path with regular expression for query string in url
React Router - path with regular expression for query string in url

Time:12-07

My application paths are defined as follows

domain_url/mtr/1234?type=c
domain_url/mtr/1234?type=sm
domain_url/mtr/1234?type=smd

I am handling the routing as follows. This one is working fine

<Route path='/mtr/:id' element={<Component />} />

Now my requirement is I have to enable only the following path

domain_url/mtr/1234?type=c

Currently, we are not exposing the other two paths.

I tried the route path as follows

<Route path='/mtr/:id?type=c' element={<Component />} />

I am getting No routes matched location "/mtr/1234?type=c" error.

I'm using react-router@4.

CodePudding user response:

The <Route> element should capture the path without the query parameter

i.e. :

<Route path='/mtr/:id' element={<Component />} />

The link to the route can have the query param

<Link to="/mtr/12345?type=c">Netflix</Link>

the component handling the the specific route (in this case <Component/> ) can access this query parameer

import { useSearchParams } from "react-router-dom";
...
const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("type")

and do the required filtering / logic required

see working example here: link

CodePudding user response:

Route paths only care about the path part of a URL, the queryString is ignored for route path matching. You'll just need to validate the queryString values in the component and handle accordingly.

Example:

Since you originally tagged react-router@4

<Route path='/mtr/:id' component={Component} />
const Component = ({ history, location }) => {
  const searchParams = new URLSearchParams(location.search);
  const type = searchParams.get("type");
  
  React.useEffect(() => {
    if (type.toLowerCase() !== "c") {
      history.back();
    }
  }, [history, type]);

  ...
};

The Route component is using react-router@6 syntax/API though, so just in case you are using v6.

<Route path='/mtr/:id' element={<Component />} />
import { useNavigate, useSearchParams } from 'react-router-dom';

...

const Component = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const type = searchParams.get("type");
  
  React.useEffect(() => {
    if (type.toLowerCase() !== "c") {
      navigate(-1);
    }
  }, [navigate, type]);

  ...
};
  • Related