Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
React Router Quick Start Guide

You're reading from  React Router Quick Start Guide

Product type Book
Published in Sep 2018
Publisher Packt
ISBN-13 9781789532555
Pages 156 pages
Edition 1st Edition
Languages
Author (1):
Sagar Ganatra Sagar Ganatra
Profile icon Sagar Ganatra

Table of Contents (10) Chapters

Preface 1. Introduction to React Router 4 and Creating Your First Route 2. Configuring Routes - Using Various Options in the Route Component 3. Using the Link and NavLink Components to Navigate to a Route 4. Using the Redirect and Switch Components 5. Understanding the Core Router, and Configuring the BrowserRouter and HashRouter components 6. Using StaticRouter in a Server-Side Rendered React Application 7. Using NativeRouter in a React Native Application 8. Redux Bindings with connected-react-router 9. Other Books You May Enjoy

Using the Link and NavLink Components to Navigate to a Route

React-Router provides the <Link> and <NavLink> components, which allow you to navigate to different routes defined in the application. These navigation components can be thought of as being like anchor links on the page that allow you to navigate to other pages in the site. In a traditional website, when you navigate through the application using anchor links, it results in a page refresh, and all the components in the page are re-rendered. Navigation links created with <Link> and <NavLink> do not result in a page refresh, and only those certain sections of the page that are defined using the <Route> and match the URL path are updated.

Similar to a <Route> component, the navigation components <Link> and <NavLink> are React components that allow you to define navigation...

<Link> component

A <Link> component is used to navigate to an <indexentry content=" component:about"> existing route that is defined using the <Route> component. To navigate to a route, specify the pathname used in the route as a value to the to prop:

import { Link } from 'react-router-dom';

class App extends Component {
render() {
return (
<div class="container">
<nav>
<Link to="/">Home</Link>
<Link to="/dashboard">Dashboard</Link>
</nav>
<Route
path="/"
component={HomeComponent}
exact
/>
<Route
path="/dashboard"
...

<NavLink> component

The <NavLink> component is similar to the <Link> component, except that several props can be specified that help you to conditionally add styling attributes to the rendered element. It accepts the same set of props as the <Link> component (to, replace, and innerRef) for navigating to a route, and it includes props to style the selected route.

Let's take a look at these props that help you style the <NavLink> component.

activeClassName prop

By default, the class name active is applied to the active <NavLink> component. For example, when a <NavLink> is clicked and the corresponding route is rendered, the selected <NavLink> has its class name set to active...

Navigating to nested routes

In the last chapter, we saw how to create nested routes using the match prop that the rendered component receives. The match.url property contains the browser's URL path that matched the <Route> component's path. Similarly, the <Link> and <NavLink> components can be used to create navigation links to access these nested routes:

<nav>
<Link
to={`${match.url}/pictures`}>
Pictures
</Link>
<NavLink
to={`${match.url}/books`}
activeStyle={{
background: 'orange'
}}>
B
ooks
</NavLink>
</nav>

In the preceding code snippet, the <Link> and <NavLink> components make use of match.url to get a reference to the current rendered route and add the additional path values required to navigate to the nested route.

...

Navigating to a route programmatically using history

The <Link> and <NavLink> components render anchor links on the page, which allow you to navigate from the current route to the new route. However, in many cases, the user should be navigated to a new route programmatically when an event occurs. For example, the user should be navigated to a new route upon clicking the Submit button in the login form. The history object available to the rendered component can be used in such cases:

export const DashboardComponent = (props) => (    
<div className="dashboard">
Inside Dashboard route
<button onClick={() => props.history.push('/user')}>
User
</button>
</div>
);

Here, the DashboardComponent receives props as its argument, which contains the history object. The onClick handler calls...

Using the withRouter higher–order component

The history object is available to the component rendered with a <Route> match. In the preceding example, the DashboardComponent was rendered as a result of navigation to the path /dashboard. The rendered component received the props, which contained the history object (as well as match, location, and staticContext). In a case where, the rendered component on the page is not the outcome of a route navigation, the history object will not be available to the component.

Consider a FooterComponent included in App.js :

class FooterComponent extends Component {
render() {
return (
<footer>
In Footer
<div>
<button
onClick={() =>
this.props.history.push('/user')}>
...

Preventing transitions with <Prompt>

When you navigate between the pages in the application, the transition to the new route occurs instantly. However, there are scenarios in which you want to prevent this transition based on the state of the application. One such common example is when a user has entered data into form fields and has spent several minutes (or hours) filling up the form data. If the user clicks on a navigation link accidentally, all the data entered in the form will be lost. The user should be notified of this route navigation, so that the user gets a chance to save the data entered into the form.

Traditional websites keep track of the state of the form and display a confirmation message when the user tries to navigate away from a page that contains a form that has not been submitted to the server. In these scenarios, a confirmation dialog box is shown with...

Summary

In this chapter, we looked at how the <Link> and <NavLink> navigation components can be used to navigate to various routes defined in the application. These components render anchor links in the page, and, when the user clicks on these links, sections of the page are updated as opposed to doing a complete page reload, thus providing a lucid user experience. The <Link> component accepts the props to, replace, and innerRef.

The <NavLink> component is similar to the <Link> component, and it accepts all the props that the <Link> component works with. In addition to adding a link to the page, the <NavLink> component accepts several props—activeClassName, activeStyle, exact, strict, and isActive.

To create links to the nested routes, the <Link> and <NavLink> components can use the prefix match.url in the to prop....

lock icon The rest of the chapter is locked
You have been reading a chapter from
React Router Quick Start Guide
Published in: Sep 2018 Publisher: Packt ISBN-13: 9781789532555
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}