This getting started assumes you are working with create-react-app, or something equivalent using Babel and all the goodies out there.
Also check out the great documentation right here.
First, install react-router-dom:
npm install react-router-dom or yarn add react-router-dom.
Then, create a component that exists of a basic Navbar with two items and basic pages:
import React from 'react'
import { BrowserRouter, Route, Link } from 'react-router-dom'
const Home = () => (
<div>
<p>We are now on the HOME page</p>
</div>
)
const About = () => (
<div>
<p>We are now on the ABOUT page</p>
</div>
)
const App = () => (
<BrowserRouter>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<hr/>
<Route path="/" component={Home}/>
<Route path="/about" component={About}/>
</div>
</BrowserRouter>
)
export default App
Let's go step by step through this code:
import React from 'react': Make sure you import Reactimport { BrowserRouter as Router, Route, Link } from 'react-router-dom' split up:BrowserRouter is the actual router itself. Make sure to wrap your component within the BrowserRouter component.Route is one particular route that can be navigated toLink is a component that produces an <a href="..."> tag, which you can use as a hyperlink.const Home is a function that returns the homepage.const About is a function that returns the About page.const App is the main component:
<BrowserRouter> is the JSX component that wraps the components in which you want to use the <Route> component.
'is a single element to wrap all JSX inside theBrowserRouter` in.
<ul> is the Navbar. It contains a link to Home and a link to About.
<li><Link to="/">Home</Link></li> links to the homepage. You can see that, since the link refers to "/", an empty relative path renders the homepage.
<li><Link to="/about">About</Link></li> links to the About page.
<Route path="/" component={Home}/> describes which component should be rendered if the relative path is "/".
<Route path="/about" component={About}/> describes which component should be rendered if the relative path is "/about".
Lot to learn from here, but hopefully this explains the fundamentals, so from here you can continue your learnings.