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
- create-react-app react-routing-with-bootstrap4
- npm start
So when you execute above command using command prompt or power shell, now we can create a new reactjs app using the following command.
When we run above command, you can see that our project will be created and run the application by using following npm command.
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.
- {
- "name": "react-routing-with-bootstrap4",
- "version": "0.1.0",
- "private": true,
- "dependencies": {
- "react": "^16.5.1",
- "react-dom": "^16.5.1",
- "react-scripts": "1.1.5"
- },
- "scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test --env=jsdom",
- "eject": "react-scripts eject"
- }
- }
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
- npm install react-router-dom
- npm install react-bootstrap
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.
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.
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.
- Home.js
- About.js
- 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.jsAbout.js
- import React from 'react';
- const Home = () => (
- <div>
- <h1>This Is From Dashboard Page</h1>
- </div>
- )
- export default Home;
Contact.js
- import React from 'react';
- const About = () => (
- <div>
- <h1>This Is From About Us Page</h1>
- </div>
- )
- export default About;
- import React from 'react';
- const Contact = () => (
- <div>
- <h1>This Is From Contact Us Page</h1>
- </div>
- )
- 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.
- import React, { Component } from 'react';
- import './App.css';
- // ract-bootstrap components
- import { Navbar, Nav, NavItem, MenuItem, NavDropdown } from 'react-bootstrap';
- // Our speperately created components
- import Home from './Components/Home';
- import About from './Components/About';
- import Contact from './Components/Contact';
- // To use routing functionalities
- import { Link, Switch, Route } from 'react-router-dom';
- class App extends Component {
- render() {
- return (
- <div className="App">
- <Navbar>
- <Navbar.Header>
- <Navbar.Brand>
- <a>Routing With React-Router</a>
- </Navbar.Brand>
- </Navbar.Header>
- <Nav>
- <NavItem href="javascript:void(0)">
- <Link to="/">Dashboard</Link>
- </NavItem>
- <NavItem href="javascript:void(0)">
- <Link to="/about">About Us</Link>
- </NavItem>
- <NavItem href="javascript:void(0)">
- <Link to="/contact">Contact Us</Link>
- </NavItem>
- </Nav>
- </Navbar>
- <Switch>
- <Route exact path='/' component={Home} />
- <Route path='/about' component={About} />
- <Route path='/contact' component={Contact} />
- </Switch>
- </div>
- );
- }
- }
- 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.
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
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
- <meta name="theme-color" content="#000000">
- <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
- <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
- <!-- Bootstrap CDN Files -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
- crossorigin="anonymous">
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
- crossorigin="anonymous">
- <!-- End -->
- <title>React App</title>
- </head>
- <body>
- <noscript>
- You need to enable JavaScript to run this app.
- </noscript>
- <div id="root"></div>
- </body>
- </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.
- import { BrowserRouter } from 'react-router-dom';
And the complete code will look like this for the file index.js.
- import React from 'react';
- import ReactDOM from 'react-dom';
- import './index.css';
- import App from './App';
- import registerServiceWorker from './registerServiceWorker';
- import { BrowserRouter } from 'react-router-dom';
- ReactDOM.render(
- <BrowserRouter>
- <App />
- </BrowserRouter>, document.getElementById('root'));
- 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 startHow 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.
Clicking on about us link, you will have a screen like this.
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.