Introduction
React-Router is a routing library for react js. This is important if you want to build single page application.
The reason that you want routing to be on the frontend is mainly for user experience. It reduce the loading time because the web app has been initally loaded in the beginning.
A good example of this is the angular 4 website. (link) You will notice that the website doesn’t load. (hint: you can see the refresh bottom doesn’t change)
Front end routing has pros and cons. The pros are great for user experience so that the web app performs like native apps. The cons are that your web app is not SEO friendly. Some SEO crawler does not read javasript well.
How to use it
Create a App.js(some use route.js)
import router related components & our Components
1
2
3
4
5
6
7
8
9
10
11
12
13// import router related components
import {
BrowserRouter as Router,
Route,
Switch,
} from 'react-router-dom'
// import our components
import Nav from 'containers/Nav/Nav'
import MovieList from 'containers/MovieList/MovieList'
import MovieShow from 'containers/MovieShow/MovieShow'
import NotFound from 'components/NotFound/NotFound';
import Footer from 'components/Footer/Footer';Set up our routes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class App extends Component {
render() {
return (
<Router>
<div>
<Nav />
<Switch>
<Route exact path="/" component={MovieList}/>
<Route path="/movie/:id" component={MovieShow}/>
<Route component={NotFound}/>
</Switch>
<Footer />
</div>
</Router>
);
}
}import to our index.js
1
2
3
4
5
6
7
8
9import App from './App';
...
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
** Some important notes
We link our routes with the component that it refers to. For example the route “/movie/:id” is link to the MovieShow component.
exact means that the path must be exactly or it will load anything with “/“
is unique in that it renders a route exclusively. There’s more desciption on react router api. Link