React router

Introduction

React Router is a standard React library that enables navigation among views of various components in a React Application. It keeps the UI in sync with the URL.

To understand it better, let us first create a React application.

First, install create-react-app and let us call it ninjasApp

 


 

 

STEP 1:Build a React Application.

 


 

In the src folder, create one file called App.js and add the below-given code into it.

 

import React, { Component } from 'react';

 

class App extends Component {
  render() {
    return (
        <div>
          <h2>Welcome to Coding Ninja’s React Router Tutorial</h2>
        </div>
    );
  }
}

export default App;

 

 

 

 

 

 

 

Installation

You can install React Router with either npm or yarn. Since we’re building a web app, we’ll use react-router-dom in this guide.

Now, in the main.js file, add the following into it.

// main.js
import React from ‘react’;
import ReactDOM from 'react-dom';
import App from ‘./App’;

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

 

 

 

 

Primary Components

There are three categories of components in React Router:

  • routers, like <BrowserRouter> and <HashRouter>
  • route matchers, like <Route> and <Switch>
  • and navigation, like <Link>, <NavLink>, and <Redirect>

 

Routers

To handle the dynamic request, use BrowserRouter, and to serve the static request, use HashRouter.

 

All of the components that you use in a web application should be imported from react-router-dom.

 

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

 

Every Router in React creates a history object to keep track of the current location of the page.

To Render-

 

// Add this in main.js
import { BrowserRouter } from 'react-router-dom'
import App from './App';

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

 

 

 


 

 

STEP 2: Make Three Components to render 

 

 


 

 

Firstly, make one component directory.

Add Home.js component in that.

 

// Home.js
import React, { Component } from 'react';

class Home extends Component {
  render() {
    return (
        <div>
          <h2>Home Page</h2>
        </div>
    );
  }
}
export default Home;

Now, make the About.js component.

// About.js
import React, { Component } from 'react';

class About extends Component {
  render() {
    return (
        <div>
          <h2>Learn about React Routers</h2>
        </div>
    );
  }
}
export default About;

Lastly, make the Contact.js component.

// Contact.js
import React, { Component } from 'react';

class Contact extends Component {
  render() {
    return (
        <div>
          <h2>Contact me to learn more</h2>
        </div>
    );
  }
}
export default Contact;

 

 


 

 

STEP 3: Register the routes in the App.js file


 

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

import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';

class App extends Component {
  render() {
    return (
    <Router>
        <div>
          <h2>Welcome to React Router Tutorial</h2>
          <nav className="navbar navbar-expand-lg navbar-light bg-light">
          <ul className="navbar-nav mr-auto">
            <li><Link to={'/'} className="nav-link"> Home </Link></li>
            <li><Link to={'/contact'} className="nav-link">Contact</Link></li>
            <li><Link to={'/about'} className="nav-link">About</Link></li>
          </ul>
          </nav>
          <hr />
          <Switch>
              <Route exact path='/' component={Home} />
              <Route path='/contact' component={Contact} />
              <Route path='/about' component={About} />
          </Switch>
        </div>
      </Router>
    );
  }
}
export default App;

The final main.js file will look like-.

// main.js

import React from 'react';
import { render } from 'react-dom';
import App from './App';

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

 

The index.html file looks like-.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans|Roboto" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <title>React Router Tutorial</title>
</head>
<body>
    <div id="App" class="container"></div>
</body>

</html>

So, finally, the output is working, and you can navigate the routes and see that output is changing. To get the full code, check the following tutorial link.

Output:

 

  1. After running the main.js file, the following screen will appear:

 

 

Now you can navigate to any of the three components, and the following output screen will be there :

 

  1. Home

 

  1. Contact 

 

  1. About

 

Route Matchers

Switch and Route are the two Route matching components. When a <Switch> is produced, it looks for an <Route> element whose path matches the current URL among its descendants. It renders that Route> and ignores all others when it finds one. This indicates that more precise (and usually longer) routes should be placed before less specific ones. The <Switch> does nothing if no <Route> matches (null)

 

Navigation or Router Changers

To construct links in your application, React Router provides a <Link> component. An anchor <(a>) will be rendered in your HTML document anywhere you render a <Link>. 

The <NavLink> is a particular type of < Link> that can style itself as “active” when its to prop matches the current location.

 

To learn more about Route Matchers and NAvigation, click on the following link.

 

Frequently asked Questions

Q1: What is react-router used for?

Ans: React routers are used to define multiple routers in a React-based web application. When a user types a specific URL into their browser, and that URL path matches one of the 'routes' in the router file, the user is routed to that Route.

Q.2 Do I need a react-router?

Ans: No, React Routers are not compulsory. However, it is rich with navigational components, which can be very useful for larger and more complex navigational requirements in React applications. 

Q.3 Is react-router official?

Ans: Yes, it is an official and standard routing package in React.

Q.4 Why do we need a react router Dom?

Ans: You can use React Router DOM to construct dynamic routing in a web app. React Router DOM supports component-based routing according to the needs of the app and platform, unlike traditional routing architecture, which handles routing in a configuration outside of a running app.

 

Key Takeaways

 

Today, we learned about how to use a React router to redirect React applications.

We learned about react routers’ three primary components: routers, route matchers, and navigation. Then we constructed a browser router application and learned how to use routers to navigate.

To learn React.JS in detail, Coding Ninjas provide this amazing course. Enroll today and build amazing web applications.

 

By- Gazal Arora

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think