React Router DOM v4 Tutorial (with Examples) React

React Router DOM Tutorial (with Examples)
Introduction
In this tutorial we are going to get you started with react-router-dom using an example React application showing you how to use different concepts such as Link and NavLink for creating links (instead of anchors) in the React way, Switch and exact for enabling exclusive routing and browser routing history.

Perhaps the most suitable way to see how React Router v4 works is by writing a simple multiple-page React app using the new router concepts. Our example app will have routes to home, about, contact, login, register and profile components/pages. But first lets have a tour of React Router v4 concepts and how they differ from React Router v3?

React Router v4 vs React Router v3
Before v4 there was React Router v3, React router v4 is a complete re-write so what's the difference between these two React routers? here is a summary list of most differences:

With React router v4, routing is not centralized anymore instead it becomes a part of the rest of the app layout and UI.
Browser specific routing components live in react-router-dom instead of react-router so imports need to be changed to be from react-router-dom package.
Introducing new components such as BrowserRouter and HashRouter for specific use cases (see below).
No more use of {props.children} for nesting components in v4 React Router.
React Router v3 routing rules were exclusive meaning only one route will be matched at one time. For v4, routing rules are inclusive meaning multiple routes can be matched and then rendered.
React-router-dom is the version of React Router v4 designed for web applications, React Router v4 was divided into three packages:

react-router: common core components between dom and native versions.
react-router-dom: the dom version designed for browsers or web apps.
react-router-native: the native version designed for react-native mobile apps.
react-router vs react-router-dom vs react-router-native
react-router hosts the core components for routing for React applications, react-router-dom provides browser specific components for routing web apps and react-router-native provides specific components for react-native or mobile apps created with React Native. So you should either install react-router-dom or react-router-native as both export their corresponding environments components plus what react-router exports.

Installation
Since we are building a web application not a native mobile app we need to install react-router-dom package, so inside your React project run the following command using your terminal (Linux or MAC) or command prompt (Windows):

npm install --save react-router-dom
Understanding and Using Routers
BrowserRouter: This is a sub-class or a concrete implementation of Router interface that makes use of HTML5 history API to sync your UI with the current browser's url or actually the url's path i.e window.location.
HashRouter: Just like the previous router but only uses the hash part of the URL i.e window.location.hash.
MemoryRouter
NativeRouter: Used for routing inside react-native mobile apps.
StaticRouter: Used for static routing just like React Router v3.
BrowserRouter vs HashRouter
There are many types of Router components, among them < BrowserRouter > and < HashRouter > for client side React apps. If you are using a dynamic server that can handle dynamic URLs then you need to use the BrowserRouter component but if you are using a server that only serves static files then a HashRouter component is what to be used in this case.

Understanding and Using Routes
The < Route > component is one of the most useful components of React Router v4 and the idea behind it is simple, wherever you want to render something when only there is a match with the location's path you can use a Route component.

The Route component takes many properties such as:

path property: of type string, it holds the name of path to be matched.
component property: it holds the name of the component to be rendered if there is a match.
exact property: this property tells Route to exactly match the path (see inclusive and exclusive routing)
strict property: this property tells Route to match only a path that has a trailing slash.
There are two other properties which can replace the component property to tell the Route component what it needs to render when there is a match:

render property:a function that return a React element. More useful for inline rendering or for wraping rendered component.
children: also a function which renders a React element. Except that this one will always render even if there is no path match.
Most of the times, you will use component propery but there are also many situations when you'll have to use either render or children properties instead. Thre three methods will be passed these three props:

match
location
history
For example:

Using component:

Will render the HomePage component when browser's location path matches exactly /.

Using render:

For inline rendering:


Home

}/>
For wrapping:

const FadingRoute = ({ component: Component, ...rest }) => (
(

)}/>
)

Using children:

const ListItemLink = ({ to, ...rest }) => (
(

)}/>
)
For more information about how React Router v4 matchs paths see path-to-regexp the module used for matching paths.

URL/Path/Route Parameters
Usually there are variable parts of the pathname used to pass information between diffrent routes of an application so how do we capture these variables and pass them to components? We can just append the name to be used for the variable plus a colon : to the end of the route's path, for example:

const Home = ({ match }) => (

Parameter 1 : {match.params.param1}



)
When there is a path match an object which has the following properties will be created and passed to the component:

url: the matched part of the URL.
path: simply the path.
isExact: equals True if path equals exacly the current location's path-name.
params: an object containing URL parameters.
Understanding and Using Links
Links are React Router v4 components designed as a replacment of anchor links to create navigation elements which enable users to navigate between differenet pages of React apps. Unlike anchors ,which reloads the whole page, Links only reload the portion(s) of the UI that match(s) the browser's location path.

A Link component takes a to property which tells React Router the destination to navigate to. For example:

import { Link } from 'react-router-dom'
const Nav = () => (
Home )
When clicked will take us to location with path: /

the to prop can either take a string or a location (pathname, hash, search, and state) object, for example:

Link can take also another property: replace if True, when clicked the link entry will be replaced in the history.

< Link > vs < NavLink >
NavLink is a subclass of Link which adds styling information to the rendered element(s), for example:

import { NavLink } from 'react-router-dom'

My Profile Writing our First Example with React Router DOM
Now lets write an example React app which shows you how to use BrowserRouter to implement routing.

First we import the necessary routing components such as Route and BrowserRouter

import { BrowserRouter } from 'react-router-dom'
import { Route } from 'react-router-dom'
Next we create the base layout component, besides common HTML tags we also use React Router v4 components Link and Route:

const BaseLayout = () => (


React Router v4 Browser Example




React Router v4 Browser Example (c) 2017

)
Next we create our pages:

const HomePage = () =>
This is a Home Page

const LoginPage = () =>
This is a Login Page

const RegisterPage = () =>
This is a Register Page

const ProfilePage = () =>
This is the Profile Page

const AboutPage = () =>
This is an About Page

const ContactPage = () =>
This is a Contact Page

And finally we create the App component which BrowserRouter component to hold our base layout component then render the app.

const App = () => (

)
render(, document.getElementById('root'))
As you can see, it's very easy to use the React Router v4 components to create apps with routing.

Understanding Inclusive Routing
In our example app we used the prop exact in the Route for component HomePage

That's because React Router v4 uses inclusive routing instead of exclusive routing used by React Router v3 so without exact property the home component will be rendered with all other components, for example when the user visits /login path both / and /login paths will be matched and their corresponding components LoginPage and HomePage will be rendered. But that's not the behavior we are looking for, that's why we need to add the exact prop which tells the Route component to match exactly the / path.

Now lets see how we can use inclusive routing in our advantage, lets suppose we have a sub-menu component that needs to be available only when we are on the profile page We can easily change our basic layout to add this requirment:

const BaseLayout = () => (


React Router v4 Browser Example
Post a Comment
Powered by Blogger.