React-Router

Photo by Gabriel Sollmann on Unsplash
npm install react-router-dom
  • First import BrowserRouter and Route from react-router-dom.
  • BrowserRouter is commonly renamed as Router
// .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')
);

One of the most Important Components

Photo by Matt Duncan on Unsplash

<Route>

What happens here in the Route component is that when the URL matches this specified path, it will render this specified component.

<Router>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
</div>
</Router>)

<NavLinks>

Photo by Clark Tibbs on Unsplash
  • Both update the browser URL
  • Render the Route component.
  • NavLink acts like Link, 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>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store