'react-router-dom v6 params only numbers

I want add number regex in may param in react-router-dom v6. it work fin in v5 like it:

 <Route path="list/:id(\d+)" element={<MyComponent/>} /> 

but it not work in v6.



Solution 1:[1]

Regular expressions are not supported in react-router-dom@6.

See What Happened to Regexp Routes Paths?

Regexp route paths were removed for two reasons:

  1. Regular expression paths in routes raised a lot of questions for v6's ranked route matching. How do you rank a regex?

  2. We were able to shed an entire dependency (path-to-regexp) and cut the package weight sent to your user's browser significantly. If it were added back, it would represent 1/3 of React Router's page weight!

You can use the useParams hook and test the id param in the component.

Example:

import { useParams, useNavigate } from 'react-router-dom';

const MyComponent = () => {
  const { id } = useParams();
  const navigate = useNavigate();

  useEffect(() => {
    if (!/\d+/.test(id)) {
      navigate(-1);
    }
  }, [id, navigate]);

  ...
};

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 Drew Reese