In this blog, I'm going to develop a small POC in React using React-Dom-Router. Routing becomes very important as an application grows, especially for handling the navigation from one component to another. I will be covering the basics using Stateful and Stateless components.
Follow the below npm commands.
- npm install -g create-react-app // To install react library for React development
- npx create-react-app my-app_Demo //create new react application
- npm install --save react-router-dom // router comes in different package
Let's import the route-related class.
- import { BrowserRouter as Router, NavLink, Route, Switch } from 'react-router-dom';
BrowserRouter
It's like a parent React component which keeps an eye on the URL changes.
- <Router>
- <NavLink>Your Code goes here</NavLink>
- <Route path="/blog" exact strict component={Blog} />
- lt;/Router>
Route
Based on the URL passed by the parent, it will render other component as per as its matching component.
- <Route path="/blog" exact strict component={Blog} />
NavLink
It's just a new version of <Link>. To use an active route class, we commonly use NavLink.
- <NavLink to="/about" className="nav-link" exact activeStyle={{ color: "black" }} >
It's a simple navigation button; on click of this link, it will redirect to the "/about" component.
exact
This means the URL should be "localhost:3000/about". If you don't put the exact one, it can throw an error. If http://localhost:3000/ is used, it will match "/" and render the Home component as well.
Note
Use exact only when there are no nested routes for the specified path. Here's the complete code.
match: will help you to read the URL parameters.
- <Router>
- <NavLink to="/urlpara/255066" className="nav-link" exact>Test URL Parameters</NavLink>
- <Route path="/urlpara/:id" exact strict component={UrlPara} />
- </Router>
The component code goes as below for reading the URL parameters.
- import React, { Component } from 'react';
-
- class UrlPara extends Component {
- render() {
- return (
- <div>
- User Navigated to : {this.props.match.params.id}
- <p>
- match contains : ${JSON.stringify(this.props.match,null,4)}
- </p>
- </div>
- );
- }
- }
-
- export default UrlPara;
Let's see the output in the browser.
Switch()
Also, we need to make sure that only one component renders at a time.
- <Switch>
- <Route path="/blog" exact strict component={Blog} />
- <Route path="/contact" exact strict component={Contact} />
- </Switch>
Above is the complete demo POC with a highlighted section of React routing concepts.