Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]);

  ...
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading