Routing Part-3


In this article, we will continue discussing about Routing. This is Continuation to our Previous. 

If we take a look at the Output of Program, we have three different links and we are able to Navigate to different Components. 

Lets say we want to add some styling attributes to the Particular link when it is active, so it becomes easy for a user to identify which link he has Clicked. 

React Router Provides another Component Called as NavLink which is a  special type of <Link> that can style itself as “active” when its to property value matches the current location.

Lets open index.html and add a new css class. 

<style>
        .testClass{
           font-weight:bold;
           color: red;
         }
    </style>

Lets go back to index.js, we will import NavLink Component. 

For Departments and Projects, instead of using Link Component, lets use NavLink and we will use a New Property called as activeClassName. To this we will pass the css class we created. 

<ul>
        <li><Link to="/">Employees</Link></li>
        <li><NavLink to="/departments" activeClassName="testClass">Departments</NavLink></li>
        <li><NavLink to="/projects" activeClassName="testClass">Projects</NavLink></li>
 </ul>

Save the Changes, Navigate to the browser. When we click on Departments link, we can see that that link is styled. 

There are some possibilities that at times our application might generate some broken links or if user go and directly enter the Navigation URL, if that component doesnot exist, we can redirect users to specific component and display the message that this component doesnot exist. 

Lets go ahead and Create a Component which is used for Displaying the Page Not Found message. 

Now to the List of Routes, add one more Route Element at the end and set the Component value as Error Component. It will not have any specific path as such.

Remember to keep this at the end as this Route doesnot have any path. Else for any Navigation, our router shows up this Error Component. 

Order of the Routes do play important role.

<Switch>
        <Route exact path="/" component={Employee}></Route>
        <Route path="/departments" component={Department}></Route>
        <Route path="/projects" component={Project}></Route>
        <Route component={InvalidPath}></Route>
      </Switch>

Save the Changes, navigate to the browser. Now if we try to enter any other Navigation URL, Error Component Contents will be displayed. 

Video Reference:





© 2020 Pragimtech. All Rights Reserved.