Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does react-router treat a regex `path` correctly, but throws an error at the same time?

I have a component that I want to be displayed on all the paths except for root path. So instead of providing all the paths to the Route component, I wrote this:

<Route exact path={/^\/.+$/} component={() =>
  <div><img src="../../../assets/AndreyBogdanov2.jpg" className="me" /></div>
} />

That regex matches all the strings that have any character after the slash in the beginning. And it works as expected, however, in the console I see an error:

Warning: Failed prop type: Invalid prop `path` of type `regexp` supplied to `Route`, expected `string`.
    in Route (created by App)
    in App
    in Router (created by BrowserRouter)
    in BrowserRouter

Not that I'm complaining, but I would like to know, how come it works?

In the docs for the path prop it says that it needs to be any URL that path-to-regexp understands, and in the path-to-regexp's docs, it says that regex is a valid parameter. So basically, it's the component's PropTypes that throws the error when it encounters something other than a string.

like image 955
JaffParker Avatar asked Mar 07 '23 04:03

JaffParker


1 Answers

It is because it can only accept a string value. You also need to insert something that path-to-regexp can read as described in React Router Training. You can look for how to write valid regexes in their repository here.

like image 191
Hugo Nasciutti Avatar answered Mar 10 '23 09:03

Hugo Nasciutti