Site icon Tutorial

Route Matching

A route has three attributes that determine whether or not it “matches” the URL:

Nesting

React Router uses the concept of nested routes to let you declare nested sets of views that should be rendered when a given URL is invoked. Nested routes are arranged in a tree-like structure. To find a match, React Router traverses the route config depth-first searching for a route that matches the URL.

Path Syntax

A route path is a string pattern that is used to match a URL (or a portion of one). Route paths are interpreted literally, except for the following special symbols:

<Route path=”/hello/:name”>         // matches /hello/michael and /hello/ryan

<Route path=”/hello(/:name)”>       // matches /hello, /hello/michael, and /hello/ryan

<Route path=”/files/*.*”>           // matches /files/hello.jpg and /files/hello.html

<Route path=”/**/*.jpg”>            // matches /files/hello.jpg and /files/path/to/file.jpg

<Route path=”/hello\\(:name\\)”>    // matches /hello(michael)

If a route uses a relative path, it builds upon the accumulated path of its ancestors. Nested routes may opt-out of this behavior by using an absolute path.

Precedence

Finally, the routing algorithm attempts to match routes in the order they are defined, top to bottom. So, when you have two sibling routes you should be sure the first doesn’t match all possible paths that can be matched by the later sibling. For example, don’t do this:

<Route path=”/comments” … />

<Redirect from=”/comments” … />

Exit mobile version