BUILD YOUR FIRST REACTJS ROUTER
HOW TO GET STARTED WITH ROUTING IN REACTJS
Routing in ReactJs can be done using a very popular npm package called react-router-dom. You can view official site npm package
Install and import package and various components
npm install react-router-dom
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Error from './Error';
import Navbar from './Navbar';
Declare a router Component
const ReactRouterSetup = () => {
return <Router>
</Router
};
Add your first route inside Router Component
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
'/' is for home '/about' is for about page
What is Exact Keyword??? Notice the exact keyword in Home route. 'exact' is used because it will only take '/' as a route. Without 'exact' home component will be visible in all routes as all routes contains '/'.
What if someone enters a wrong route say for Ex '/hello' For that, we can add a universal route:
<Route path="*">
<Error />
</Route>
We can make an error component and whenever a user enters a wrong route an Error page will be displayed.
We also need a navbar component for showing these routes on all pages as links
Make a navbar.js file for navbar
import React from 'react';
import { Link } from 'react-router-dom';
const Navbar = () => {
return <nav>
<ul>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/about'>About</Link>
</li>
</ul>
</nav>;
};
export default Navbar;
What is 'Switch' We need Switch because it will stop looking for route as soon as it finds a matching route. For example: if we match /about it will stop after matching the route and take us to that about route. Without Switch we will also see other sub-routes say '/about/info' and also the universal route. So it is important to wrap the Router component inside the *Switch
FINAL CODE
const ReactRouterSetup = () => {
return <Router>
<Navbar />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="*">
<Error />
</Route>
</Switch>
</Router>
;
};
You can now make your components Home, About, Error Components.
I hope you like it. Thanks.