Learning React Router: Part 2: Using

Learning React Router

React Router (DOM) allows developers to create multiple-page projects with React through supporting using components as ‘pages’ for different URL routes.


Using <Link>

In the previous part, React Router was configured through setting up routes using the <BrowserRouter> and other components. Once configured, the component <Link> can be used to navigate around in the web application.

<Link> acts like the HTML element <a> (uses it internally, in fact), but needs an additional property, to, for indicating where the link should navigate to when used.

<Link to="/user">User</Link>

Like other components, it also needs to be imported from “react-router-dom” for use in a component or component-like function.

Consider the following code:

import React, {Component} from 'react';
import { Link } from 'react-router-dom';

class App extends Component {

  render() {
    return(
      <div>
        <p><Link to="/user">User</Link></p>
        <p><Link to="/about">About</Link></p>
      </div>
    );
  }
}

export default App;

Once imported, and a project is configured in its “index.js” to understand certain routes, the <Link> component can be imported and used as an <a> element normally would.

In fact, for a more light-weight solution for those projects generating sections where multiple links might be needed, a component-like function might be an easier solution.

Consider the following version of an “About” page using a function:

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

function About() {
    return(
        <div>
            <h1>About page</h1>
            <Link to="/user">User</Link>
        </div>
    );
}

export default About;