Easy react-router-dom example

If you want to have the concept of ‘pages’ in your React app react-router-dom is the way to go. You can also use react-router-native for React Native applications, but this post will only focus on web browsers, hence the DOM.

create-react-app

First, we need to wire up a basic React app using create-react-app.

You’ll need Node installed on your machine to run the following from your favourite terminal.

npx create-react-app router-example

This will create a directory router-heaven with your starter pack app inside.

react-router-dom

You’ll need to download the react-router-dom package. In your terminal, inside your router-heaven folder, run the following command:

npm install --save react-router-dom

Open up the App.js file in the src folder and add the following to the import section:

import { BrowserRouter, Route, Link } from "react-router-dom";

BrowserRouter

This will give us access to the BrowserRouter which we need to enclose the layout of our app. So add the following tags as the first and last tag in the return statement in App.js

<BrowserRouter>
   <div className="App">
      <header className="App-header">
         <img src={logo} className="App-logo" alt="logo" />
         <p>
            Edit <code>src/App.js</code> and save to reload.
         </p>
         <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
         >
         Learn React
         </a>
      </header>
   </div>
</BrowserRouter>

Next, we need some components that we want to access via a specific URL e.g. routerheaven.com/mars. So let’s make a component named mars and another component named snickers (creativity is my strong suit)

Create a file named Mars.js in the src folder.

import React from 'react';
class Mars extends React.Component {
   constructor() {
      super()
      this.state = {}
   }
   
   render() {
      return (
         <div>
            <h2>Welcome to Mars (the candy bar, not the planet)</h2>
         </div>
     )}
   }
export default Mars

Now, we’ll create a Snickers component Snickers.js

import React from 'react';
class Snickers extends React.Component {
    constructor() {
        super()
        this.state = {}
    }
    render() {
        return (
            <div>
                <h2>Welcome to Snickers (no funny comment to say here)</h2>
            </div>
        )
    }
}
export default Snickers

We need to update our App component and include the two new components. Let’s replace the current App render method to show our two components. We are just importing the two components and replacing the render method. The result looks like this:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter, Route, Link } from "react-router-dom";
import Mars from './Mars'
import Snickers from './Snickers'
class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Mars />
        <Snickers />
      </BrowserRouter>
    );
  }
}
export default App;

We can run npm start from the terminal to see what is displayed with this render method.

Pretty underwhelming so far. So let’s continue.

The render method above lays out the two components one after the other. We need to tell the router to display the Mars component at /Mars and the Snickers component at /Snickers

To do this we need to give each component a Route like so:

<Route path="/mars/" component={Mars} />
<Route path="/snickers/" component={Snickers} />

When we save the updated render method with just the two above items we see a blank screen. Great! This means that we need to navigate to /mars or /snickers to see the content of each page. So let’s create a Link to those next:

<BrowserRouter>
        <Link to="/mars">Mars</Link>         
        <Link to="/snickers">Snickers</Link>
        <Route path="/mars/" component={Mars} />
        <Route path="/snickers/" component={Snickers} />
</BrowserRouter>

Conclusion

To get page navigation going:

  1. Import BrowserRouter, Route and Link from react-router-dom
  2. Wrap your app in BrowserRouter tags
  3. Create a Route for each ‘page’ in the app
  4. Navigate to each ‘page’ using the Link tag

And that’s it! The most basic example of setting up pages in your React SPA.

For more information check out the official GitHub repo here

Don’t forget to check out my React page here which contains links to common concepts and examples in React.

Also, you can follow me on Twitter/X here! And now, mastodon: @bernieslearnings@mastodon.social

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments