React-Router
A Router Library..
A routing library for React, allows us to link to specific URLs then show or hide various components depending on which URL is displayed. Think of React Router, as a collection of navigational components that compose declaratively with your application.
To start using routes, you will need to install react-router-dom
:
npm install react-router-dom
To begin implementing routes:
- First import
BrowserRouter
andRoute
fromreact-router-dom
. BrowserRouter
is commonly renamed asRouter
// .src/index.js
import React from 'react';
import ReactDOM from 'react-dom';// Step 1. Import react-router
import { BrowserRouter as Router, Route } from 'react-router-dom';
const Home = () => {
return (
<div>
<h1>Home!</h1>
</div>
);
};
// Step 2.
<Router>
<Route exact path="/" component={Home} />
</Router>),
document.getElementById('root')
);
Step 1: Import BrowserRouter as Router
Step 2: The Router
(a.k.a BrowserRouter) component is the base for our application's routing. The Router
has a Route
component with two props path
and component
.
Note: exact path
prevents that route from always being rendered, no matter which route we decide to go to. So, when in doubt use exact path.
One of the most Important Components
<Route>
What happens here in the Route
component is that when the URL matches this specified path
, it will render this specified component
.
Not Finished Yet!
We forgot something
In React, a component must return one child/html node (which may wrap many others).
Simple Solution is to put all of the Route
components into a <div>
tag:
<Router>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
</div>
</Router>)
<NavLinks>
Every Route needs a Link
The React Router API provides two components that enable us to trigger our routing: Link
and NavLink
.
- Both update the browser URL
- Render the
Route
component. NavLink
acts likeLink
, you can add styling attributes to a rendered element when it matches the current URL.
import React from 'react';
import ReactDOM from 'react-dom';/* Add NavLink to importer */import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom';
/* Add styling for NavLinks */const link = {
width: '75px',
padding: '14px',
margin: '0 5px 5px',
background: 'Grey',
textDecoration: 'none',
color: 'white',
}
/* add navbar component */const Navbar = () =>
<div>
<NavLink
to="/"
/* set exact so it knows to only set activeStyle when route is deeply equal to link */
exact
/* add styling to Navlink */
style={link}
/* add prop for activeStyle */
activeStyle={{
background: 'LightGrey'
}} >Home</NavLink>
<NavLink
to="/about"
exact
style={link}
activeStyle={{
background: 'darkblue'
}} >Login</NavLink> </div>
For extra knowledge, you can visit React Router Tutorial (Links to an external site.)
Happy Coding!