HI WELCOME TO SIRIS

Routing in React using React-Router: Part1

Leave a Comment
Routing is one of the important concepts in terms of features while developing Single Page Application (SPA). Using routing we can load the view partially without loading the webpage again from the server which makes our web app very much faster in terms of performance. Routing is a kind of mechanism by which user can navigate through different URL’s available in a whole web application. But at the same time when we are developing large scale application than it is difficult to manage all the pages so for that, we can make use of routing to manage everything with ease.
In React, there is an inbuilt package called react-router which is used to implement routing in reactjs when we create a new application using create-react-app.To install and create new react app we need to install it in our system.
  • npm install create-react-app
  • So when you execute above command using command prompt or power shell, now we can create a new reactjs app using the following command.
  • create-react-app react-routing-with-bootstrap4
  • When we run above command, you can see that our project will be created and run the application by using following npm command.
  • npm start
  • A new window into a browser will automatically open and you can see that our application is up and running like that.

React-router

Now we have a new project created with the name react-routing-with-bootstrap4, and when you open the package.json file, it will look like this.
  1. {
  2. "name": "react-routing-with-bootstrap4",
  3. "version": "0.1.0",
  4. "private": true,
  5. "dependencies": {
  6. "react": "^16.5.1",
  7. "react-dom": "^16.5.1",
  8. "react-scripts": "1.1.5"
  9. },
  10. "scripts": {
  11. "start": "react-scripts start",
  12. "build": "react-scripts build",
  13. "test": "react-scripts test --env=jsdom",
  14. "eject": "react-scripts eject"
  15. }
  16. }
So as you can see into the above code snippet, we don't have the package installed called “react-router”, which is used to implement routing in react application. When we create new react app, it will not be installed automatically into our project but if you want to use this package or unable to find this package in your package.json than you can use below npm command.
  • npm install react-router
  • There is a package named react-router-dom which indirectly depends on react-router, and in this article, we are going to use this package, in order to use it, execute below npm command.
  • npm install react-router-dom
  • To design our page, I am also using another package for Bootstrap 4 which is called react-bootstrap, which provides different bootstrap 4 components for react application, just install the package using below command.
  • npm install react-bootstrap
  • So far we have covered the introduction part and also the installation part, now it’s time to implement a simple routing procedure.

Steps to configure routing

Step 1

In this simple yet effective example, we are going to work with three different pages like Dashboard, About US and Contact US.So for that create a new folder inside /src folder presented in react application and create three different files.
  1. Home.js
  2. About.js
  3. Contact.js
And in these files, we are just printing static messages, and going to export these components, for that open respective file and paste following code snippet.
Home.js
  1. import React from 'react';
  2.  
  3. const Home = () => (
  4. <div>
  5. <h1>This Is From Dashboard Page</h1>
  6. </div>
  7. )
  8.  
  9. export default Home;
About.js
  1. import React from 'react';
  2.  
  3. const About = () => (
  4. <div>
  5. <h1>This Is From About Us Page</h1>
  6. </div>
  7. )
  8.  
  9. export default About;
Contact.js
  1. import React from 'react';
  2.  
  3. const Contact = () => (
  4. <div>
  5. <h1>This Is From Contact Us Page</h1>
  6. </div>
  7. )
  8.  
  9. export default Contact;
So these three files are acts as a different page to see the routing in action, our next step is to design our user interface and for design purpose, I have used react-bootstrap components.

Step 2

After creating all those files, it’s time to implement the user interface part in which we are going to implement navigations using react-bootstrap design components. Open App.js and paste following code snippet.
  1. import React, { Component } from 'react';
  2. import './App.css';
  3.  
  4. // ract-bootstrap components
  5. import { Navbar, Nav, NavItem, MenuItem, NavDropdown } from 'react-bootstrap';
  6.  
  7. // Our speperately created components
  8. import Home from './Components/Home';
  9. import About from './Components/About';
  10. import Contact from './Components/Contact';
  11.  
  12. // To use routing functionalities
  13. import { Link, Switch, Route } from 'react-router-dom';
  14. class App extends Component {
  15. render() {
  16. return (
  17. <div className="App">
  18. <Navbar>
  19. <Navbar.Header>
  20. <Navbar.Brand>
  21. <a>Routing With React-Router</a>
  22. </Navbar.Brand>
  23. </Navbar.Header>
  24. <Nav>
  25. <NavItem href="javascript:void(0)">
  26. <Link to="/">Dashboard</Link>
  27. </NavItem>
  28. <NavItem href="javascript:void(0)">
  29. <Link to="/about">About Us</Link>
  30. </NavItem>
  31. <NavItem href="javascript:void(0)">
  32. <Link to="/contact">Contact Us</Link>
  33. </NavItem>
  34. </Nav>
  35. </Navbar>
  36. <Switch>
  37. <Route exact path='/' component={Home} />
  38. <Route path='/about' component={About} />
  39. <Route path='/contact' component={Contact} />
  40. </Switch>
  41. </div>
  42. );
  43. }
  44. }
  45.  
  46. export default App;
Here in this code snippet, I have used different markup’s to implement routing let’s see their details in depth.
Navbar : A bootstrap component which is used to implement navigation bar into our application.
Navbar.header : Contains the header part of Navbar.
Nav : It contains the list of navigation links.
Navitem : Holds separate navigation link.
Link : Is a router API which allows accessing navigation throughout the application.
Switch : It renders the child component based on the location that matches exactly the same as provided.
Route : The route is one of the most important part/component in react-router and it is used to render the user interface when any location matches.

Note

We have used react-bootstrap in our react application, for that we need to include two different style sheet, please find the below code snippet.
Public/Index.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  6. <meta name="theme-color" content="#000000">
  7. <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
  8. <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  9. <!-- Bootstrap CDN Files -->
  10. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  11. crossorigin="anonymous">
  12. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
  13. crossorigin="anonymous">
  14. <!-- End -->
  15. <title>React App</title>
  16. </head>
  17. <body>
  18. <noscript>
  19. You need to enable JavaScript to run this app.
  20. </noscript>
  21. <div id="root"></div>
  22. </body>
  23. </html>
Primarily I have included two different bootstrap CDN and the version is 3.3.7, still, we can use bootstrap 4 as well, for that just we need to search for the latest CDN files for that and include into our main index.html file.We are done with user interface part so far, our next step is very much important so let’s have a look.

Step 3

We are done with UI part, but it won’t work as expected because we have not configured our app component with the router, so for that, we need to use router API called<BrowserRouter>.

What is BrowserRouter

When we are working with the router in react, in the background it manages history API of HTML5, I mean when we routing through different pages that that time we should maintain history so that components will be available to route back again.Basically, it manages three different events which are listed below.
  • pushState
  • popState
  • replaceState
  • These events are used to manage the different routing activity using state and update accordingly, and every time it manages its own history object for each of them.
To configure BrowserRouter, we need to import the API from the package react-router-dom like this.
  1. import { BrowserRouter } from 'react-router-dom';
And the complete code will look like this for the file index.js.
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import './index.css';
  4. import App from './App';
  5. import registerServiceWorker from './registerServiceWorker';
  6. import { BrowserRouter } from 'react-router-dom';
  7.  
  8. ReactDOM.render(
  9. <BrowserRouter>
  10. <App />
  11. </BrowserRouter>, document.getElementById('root'));
  12. registerServiceWorker();
Now we are done with most of the setting which required by routing, in order to see how routing works so for that, we need to run the application using below npm command.
Npm start

How it works..

Dashboard
When we execute our application, at that time the first page will appear is Dashboard (Home) page, and you can see the output like this.
About US
Clicking on about us link, you will have a screen like this.
Contact Us
The third page is for contact us and you can see the output like this.
This is how we have implemented single level routing using react-router.
Summary
In this part of the series for react with routing, we have covered few things; let’s recap all of them quickly.
  • Introduction
  • Important packages to work with routing
  • Introduction to react-router
  • Steps to implement routing in react with bootstrap components
  • This is the basic routing tutorial in which we have developed single level routing mechanism, in our upcoming article we will learn about nested child routing in a very depth manner, meanwhile, download the code and play around it and create something amazing out of it.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.