
What is react router? Why is react router used? A easy demonstration
React-Router => React Router is a routing library for React which keeps the UI or user interface of the website in sync with the URL.
So if we hit a url say “/home”. How will react or js will come to know what the heck is /home. Is this a route ? So for this we use react router. So basically, the /home is the route. And in our codebase we will keep a route check for this. That is, when react-router encounter this URL it returns a component which is nothing but the page that we want to render.
If we want to change the pages so do this at App level. And if we want this for component level then do this in the component files. We can definitely improvise this by creating these checks in a different route.js file rather than the app.js file. For giving more clearity, there is a demonstration below.
Now, lets move on the practical, enough of theory. Since this is a library we have to install this ->
npm i react-router -S
After this, one more thing to know is the import statement which is
// using ES6 modules
import { Router, Route, Switch } from "react-router";
// using CommonJS modules
var Router = require("react-router").Router;
var Route = require("react-router").Route;
var Switch = require("react-router").Switch;
If the iFrame of the Codesandbox is not working then use the button ‘Edit on CodeSandbox”
Demonstration:
https://codesandbox.io/s/react-router-nb7w7
Stay tuned for more such blogs on react. Thank you!

Leave a comment