softare development

Working With React Router in React JS

Routing and navigation are inevitable in most software applications

The way you would handle routing and navigation in React JS is somewhat different from the way you would, let’s say, in traditional HTML.

In this tutorial we shall see how to work with React Router in React JS

So let’s get straight to the point, shall we.

1. First, you want to create your React project:

npx create-react-app yourFolderName

2. Then add the React Router dependency

yarn add react-router-dom

        or 

npm install react-router-dom

3. Next, start the app

yarn start

Let’s just design a simple nabber for our application. In your App.js (any other convenient file of your choice) add the following:

 <ul className="nav-link-style">
 <li>Home</li>
 <li>About</li>
 <li>Contact</li>
 <li>Services</li>
 </ul>

Let’s add a bit of styling our App.css

 .nav-link-style {
   display: flex;
   flex-direction: row;
   justify-content: space-evenly;
   align-items: center;
   list-style: none;
 }

Here’s our output for now:

React JS Routing and Navigation

Next, let’s add the Routing Logic

We will create a separate file and call it RouteFile (or whatever you decide to call yours, but it must not be Route or Router). This will handle our React Router We will add the following code to our RouteFile.js

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import App from '../App';


function RouteFile(){
    return(
        <Router>
            <Switch>
                <Route exact path="/" component={App} />
            </Switch>
        </Router>
    )
}

export default RouteFile;

So, here’s our routing file and we only have one Route (or navigation) here. Notice we have the word “exact” and for path we have the “/” and our component App.js. This means the App.js file is our landing page. When anyone visits our our website for the first time, they will land on the App.js file.

This is similar to our default index file in html.

What we want to do next is to create file components for other screens and link them accordingly.

Here’s what our Routing File looks like

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import About from '../About';
import App from '../App';
import Contact from '../Contact';
import Services from '../Services';


function RouteFile(){
    return(
        <Router>
            <Switch>
                <Route exact path="/" component={App} />
                <Route  path="/about" component={About} />
                <Route  path="/contact" component={Contact} />
                <Route  path="/services" component={Services} />
            </Switch>
        </Router>
    )
}

export default RouteFile;

One advantage of Routing in React JS is that we able to customise our url to something short, simple and unique.

So, here’s the full code for our App.js file

import React, { Component } from "react";
import "./App.css";
import { Link } from "react-router-dom";

class App extends Component {
 
  render() {
    return (
      <div>
        <ul className="nav-link-style">
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/contact">Contact</Link></li>
          <li><Link to="/services">Services</Link></li>
        </ul>
      </div>
    );
  }
}

export default App;

Finally, to make our Routing take effect, we need to set our RouteFile.js as the default starting component in our index.js file. Usually, the default component is App.js. But will replace that as follows:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import RouteFile from './Routes/RouteFile';

ReactDOM.render(
  <React.StrictMode>
    <RouteFile /> 
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Here’s how it works now:

Routing in React Js

Congratulations!

You have successfully added React Router to your React application.

See also

Mobile app template for mobile app developers

Author

Recent Posts

Apple is developing a doorbell camera equipped with Face ID technology.

Apple is reportedly developing a new smart doorbell camera with Face ID technology to unlock…

2 hours ago

Google Launches Its Own ‘Reasoning’ AI Model to Compete with OpenAI

This month has been packed for Google as it ramps up efforts to outshine OpenAI…

2 days ago

You can now use your phone line to call ChatGPT when cellular data is unavailable.

OpenAI has been rolling out a series of exciting updates and features for ChatGPT, and…

3 days ago

Phishers use fake Google Calendar invites to target victims

A financially motivated phishing campaign has targeted around 300 organizations, with over 4,000 spoofed emails…

4 days ago

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

5 days ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

7 days ago