Advanced Routing in React Router

In this chapter, we are going to learn advanced routing in React Router,

  • Dynamic Routes
  • Handling query params in Routing
  • Nested Routes

First, we will create a static route /topics for rendering all the topics. Then we will expand on the example to see the advanced concepts.

Let's, we will create the Topics component for the /topics page.

import React from 'react';
// topics is a static array data
import topics from './data/topics.json';

// Each topic will render this component
const Topic = ({ title, description }) => {
  return (
    <div>
      <h2>{title}</h2>
      <p>{description}</p>
      <hr />
    </div>
  );
};

// Topics page will render this component
const Topics = () => {
  return (
    <div>
      <h1>Topics List</h1>
      <hr />
      {topics.map(topic => (
        <Topic {...topic} key={topic._id} />
      ))}
    </div>
  );
};

export default Topics;

Add the /topics link in the header and route in the App.js file.

import Topics from "./Topics";

// Link to topics page
<Link to="/topics" style={{ marginLeft: '10px' }}>
  Topics
</Link>

// Route for topics
<Route exact path="/topics">
  <Topics />
</Route>

The updated App.js will be,

import React from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Topics from './topics';
import './styles.css';

export default function App() {
  return (
    <Router>
      <header>
        <Link to="/">Home</Link>
        <Link to="/about" style={{ marginLeft: '10px' }}>
          About
        </Link>
        <Link to="/topics" style={{ marginLeft: '10px' }}>
          Topics
        </Link>
      </header>
      <main>
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>
          <Route exact path="/about">
            <About />
          </Route>
          <Route exact path="/topics">
            <Topics />
          </Route>
        </Switch>
      </main>
    </Router>
  );
}

Now click the topics link on the header, you will see the new page with all topics loaded in it.