Master React Router v4: A Complete Guide to Building Dynamic and Protected Routes

This tutorial walks you through installing React Router v4, creating basic, nested, and dynamic routes, handling URL parameters, and implementing protected routes with authentication, providing comprehensive code examples and best practices for building robust client‑side navigation in modern React applications.

21CTO
21CTO
21CTO
Master React Router v4: A Complete Guide to Building Dynamic and Protected Routes

Introduction

React Router is the official routing library for React. It synchronises the UI with the browser URL, enabling single‑page applications (SPAs) to have multiple views without full page reloads.

Installation

npm install --save react-router-dom

Basic Routing

Wrap the application with BrowserRouter and define routes using Route. Use Link for navigation instead of traditional anchor tags.

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Link, Switch } from 'react-router-dom';

const Home = () => (<div><h2>Home</h2></div>);
const Category = () => (<div><h2>Category</h2></div>);
const Products = () => (<div><h2>Products</h2></div>);

class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <div className="navbar navbar-light">
          <ul className="nav navbar-nav">
            <li><Link to="/">Home</Link></li>
            <li><Link to="/category">Category</Link></li>
            <li><Link to="/products">Products</Link></li>
          </ul>
        </div>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/category" component={Category} />
          <Route path="/products" component={Products} />
        </Switch>
      </BrowserRouter>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

Exact Matching

Use the exact prop to ensure a route only matches when the URL is exactly the same.

<Route exact={true} path="/" component={Home} />

Nested Routes

Nested routes are defined inside a parent component. The parent receives match to build child URLs.

const Category = ({ match }) => (
  <div>
    <ul>
      <li><Link to={`${match.url}/shoes`}>Shoes</Link></li>
      <li><Link to={`${match.url}/boots`}>Boots</Link></li>
      <li><Link to={`${match.url}/footwear`}>Footwear</Link></li>
    </ul>
    <Switch>
      <Route exact path={match.path} component={CategoryHome} />
      <Route path={`${match.path}/:name`} render={({ match }) => (
        <h3>{match.params.name}</h3>
      ))} />
    </Switch>
  </div>
);

Dynamic Routes with Parameters

Define routes with parameters (e.g., :productId) and access them via match.params. Use render props for inline logic.

const Products = ({ match }) => {
  const linkList = productsData.map(product => (
    <li key={product.id}>
      <Link to={`${match.url}/${product.id}`}>{product.name}</Link>
    </li>
  ));
  return (
    <div>
      <h3>Products</h3>
      <ul>{linkList}</ul>
      <Route exact path={match.path} render={() => (
        <div>Please select a product.</div>
      )} />
      <Route path={`${match.path}/:productId`} render={props => (
        <Product data={productsData} {...props} />
      ))} />
    </div>
  );
};

const Product = ({ match, data }) => {
  const product = data.find(p => p.id === Number(match.params.productId));
  if (product) {
    return (
      <div>
        <h3>{product.name}</h3>
        <p>{product.description}</p>
        <h4>{product.status}</h4>
      </div>
    );
  }
  return (
    <div><h2>Sorry, product does not exist.</h2></div>
  );
};

Protected Routes (Authentication)

Use a custom PrivateRoute component that checks an authentication flag and redirects unauthenticated users to a login page.

const PrivateRoute = ({ component: Component, authed, ...rest }) => (
  <Route {...rest} render={props => (
    authed === true ? <Component {...props} /> :
    <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
  )} />
);

Login component sets the authentication flag and redirects back to the originally requested page.

class Login extends React.Component {
  state = { redirectToReferrer: false };
  login = () => {
    fakeAuth.authenticate(() => {
      this.setState({ redirectToReferrer: true });
    });
  };
  render() {
    const { from } = this.props.location.state || { from: { pathname: '/' } };
    if (this.state.redirectToReferrer) {
      return <Redirect to={from} />;
    }
    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <button onClick={this.login}>Log in</button>
      </div>
    );
  }
}

export const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true;
    setTimeout(cb, 100);
  }
};

Conclusion

The guide demonstrates how to set up React Router v4, create basic, nested, and dynamic routes, handle URL parameters, and protect routes with authentication, giving developers a solid foundation for building sophisticated client‑side navigation in React applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptReactroutingSPAReact RouterProtected Routes
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.