How to use React-router?

This answer has received 2 appreciations.

React Router has some really nice documentation. You can find it here. To quickly show you what it'll look like to setup routing with React Router:

import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, browserHistory, IndexRoute } from 'react-router'

import LayoutComponent from 'component/Layout'
import HomeComponent from 'component/Home'
import ProfileComponent from 'component/Profile'
import NotFoundComponent from 'component/NotFound'

  <Router history={browserHistory}>
    <Route path='/' component={LayoutComponent}>
      <IndexRoute component={HomeComponent} />
      <Route path='profile/:username' component={ProfileComponent} />
      <Route path='*' component={NotFoundComponent} />

This will make the following routes available:

  • / will render the Home component.
  • /profile/:username will render the Profile component where the username is dynamic.
  • * will render the NotFound component when the route doesn't match anything else.

With browserHistory you can make use of the HTML5 browser history api, allowing you to define 'clean' routes that don't contain a pound sign (#).

The LayoutComponent is a component that gets included on all pages. This way you can use headers, footers or specific containers that are required to get your styling right. A LayoutComponent can look like this:

import React, { Component } from 'react'
import Header from './Header'
import Footer from './Footer'

export default class LayoutComponent extends Component {
  render () {
    return (
      <div className='app'>
        <Header />
        <div className='container'>
          <!-- This is where your components get injected -->
        <Footer />

I strongly recommend to take a look at the documentation. It really helps understand how to use React Router and what the best practices are. Hope that answers your question! :)

Write a reply...

Stephan de Vries


Full stack developer, enthusiastic about new technologies.

Never miss an answer from Stephan de Vries,
when you sign up for Hashnode. Learn more

loading ...