shunze0925

Front-end Blog

【React】React Router v5

Shunze
3 min readFeb 6, 2021

--

The actual contents comes from UI.DEV React Router v5.

If you have interests, you can check React Router v5 by Tyler McGinnis.

What’s the mental model of React Router?

Route is gonna either render the children component if matched or it’s gonna render null.

And Route is just another component, we can render routes anywhere inside of our application.

Nested Links

If building nested links, we can use useRouteMatch hooks, it’ll return an object contains current URL pathname property.

Then we can use it to set a dynamic link rather than sticky one.

Nested Routes

useRouteMatch also return a path property, which contains current pathname preserved params.

So if we have a nested route, we can use path property to set the path of Nested Route.

Passing Props — Router v4 & v5

They both pass props into component, but in v5, we don’t have to use complicated syntax.

The only thing we need to do is to wrap our component and pass the props we want.

With Redirect, we have a declarative way to navigate rather than imperative way (history.push).

Query String

With React Router, we can grab the query string from the URL by using useLocation hooks, it’s gonna have a search property in location.

And then we can convert the string to actual value by using query string package or built-in URL search Params which comes with the browser.

404 Route

If the user come to the non-existed route, rather than showing a white screen to user, we need a component to tell user “not found” information.

By using an universal path (*), it’ll match any pattern.

So all we need to do is put the universal route to last one.

Inside of a switch, it will only render the first route that matches, if no any component match, then it will render 404 Route Component.

--

--

No responses yet