React Router

In this tutorial, we’ll make you familiar with the important concept in React known as routing, we’ll teach you how to reap the benefit of it and how to implement them in your react application.

What is Routing?

It is imperative to know, routing is an important part of the React applications. Amidst the creation of a react application, we’ll be creating multiple components. Like in our previous React tutorials, we’ve created a student, subject, and, rollno component.

Even though our react-driven application comprises of multiple components and we don’t necessarily display all of these components to our user.

For instance, we’ve created a simple react application that contains three different components namely student component, rollno component, and subject component.

When the user clicks on a Student tab, only a student component is visible to him and the rest of the components are hidden from him and the details pertaining to a student are displayed to him. Whereas if he clicks on the roll number tab, only rollno component is visible. The same is the case for the subject component.

This is where the power of the router comes into play because without incorporating routing into our react application, this kind of navigation is not possible.

Routing paves the way for navigation from one view to the next view (without leaving the page).

As it is observed, users always like to perform different tasks while surfing a web page. Therefore, in this case, interactive web apps cannot be built without routing,

In order to grasp the concept of routing and visualize it, let’s open the index.js file from our demo project. For the sake of simplicity of newbies, I kept all the React components in an index.js file.

Let’s create our first student component. To do so, create a JavaScript file in the src folder and name it student.js.

In order to make this student component accessible in other script files, we need to export this component. Now we’ll repeat the same process for the other two components.

Thereafter, we’ll create another component known as App. We’ll render this component inside our root container.

Save all these changes and navigate to the browser, you’ll see how the output will look like.

Right now, in our react app we intend to place three different links. Leveraging these links users can navigate through these components. Whether he would like to perceive student, rollno, or a subject component.

In order to get this job done, we’ll make use of routing.

In order to use routing in our react app, we have to install all the routing-related packages. In this case, we’ll use React-Router which is a very well-known library to implement routing in our react.js app.

Since we’re using routing for our web app, we’ll install it using the following command:

npm install react-router-dom

After the successful completion of an installation process, run the demo project using npm start. In order to implement react-router-dom first import all the necessary files.

In order to get this job done, we are importing BrowserRouter, Switch, Route, and Link. On the other hand, we’ll also import our student, rollno, and subject component as well.

Now let’s switch to the return method of our App component. In our code example, we want li elements to be displayed as an anchor tag.  Using these anchor tags, users can navigate through different components conveniently.

By default, react-router comes with the <Link> element to create links in your react-driven application. As you render a link in your React application, an anchor tag will automatically be rendered in your respective HTML document.

As we want our student component to be displayed by default that’s why we are using ./here.

Now we’ll implement the same strategy for the rollno and subject component. But we need to change the value of to attribute.

We can access rollno component with the help of /Rollno and subject component using /subject.

To execute each route, we must have to specify the path and the command.

Besides, it is necessary to wrap your App component in a router in order to create an enabling environment for routing for our App component.

Save all these changes and navigate to the browser to see how the output looks like:

The code for Student.js

import React from 'react';

import { useState, useEffect } from "react";




function Student() {

    

  const [students,setStudents]=useState([]);

    useEffect(()=> {

      fetch("https://localhost:44306/api/Student")

        .then(res =>res.json())

        .then(

          (result) => {

            setStudents(result);

          }

        );

    });

  

      return (

        <div>

          <h2>Student’s Complete Information </h2>

          <table>

            <thead>

              <tr>

                <th>Id</th>

                <th>Name</th>

                <th>Gender</th>

                <th>Address</th>

              </tr>

            </thead>

            <tbody>

            {students.map(std => (

              <tr key={std.Id}>

                <td>{std.Id}</td>

                <td>{std.Name}</td>

                <td>{std.Gender}</td>

                <td>{std.Address}</td>

                </tr>

            ))}

            </tbody>

          </table>

        </div>

        );

}




export default Employee

Code of Rollno.js

import React from 'react';

import { useState, useEffect } from "react";




function Department() {

    

  const [rollno,setRollno]=useState([]);

    useEffect(()=> {

      fetch("https://localhost:44306/api/Rollno")

        .then(res =>res.json())

        .then(

          (result) => {

            setRollno(result);

          }

        );

    });

  

      return (

        <div>

          <h2>Student’s roll number.</h2>

          <table>

            <thead>

              <tr>

                <th>Id</th>

                <th>Name</th>

                 <th>Roll Number</th>

              </tr>

            </thead>

            <tbody>

            {rollno.map(r => (

              <tr key={r.Id}>

                <td>{r.Id}</td>

                <td>{r.rollno}</td>

                </tr>

            ))}

            </tbody>

          </table>

        </div>

        );

}




export default Department

App.js

import React from 'react';

importReactDOM from 'react-dom';

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

import Student from './student';

importRollno from './rollno';

import Subject from './subject';




function App(){

  return(

    <div>

      <h2>Welcome to App Component..</h2>

      <ul>

        <li><Link to="/students">Students</Link></li>

        <li><Link to="/rollno">Rollno</Link></li>

        <li><Link to="/subject">subject</Link></li>

      </ul>

      <Route path="/student" component={Student}></Route>

      <Route path="/rollno" component={Rollno}></Route>

      <Route path="/subject" component={Subject}></Route>

    </div>

  )

}




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