Tutorial: Setting up react-router with Django

5 months ago I posted a problem that I was facing. Since then, I solved that problem. I received a request today to write up a tutorial showing what I did. Here is my solution:

For react-router to work with Django, you have to setup a root URL in Django. Then, you have to let react-router handles the rest.

For example, you have a Dashboard on your website that is built using React. In the Django urls.py file, this is the setting that you want to have:

url(r'^dashboard/', TemplateView.as_view(template_name="dashboard.html")),

It means that Django will handle http://your-url.com/dashboard and point that to your dashboard.html template.

Sample dashboard.html:

<!doctype html>  
<html lang="en">  
  <head>
    <meta charset="utf-8">
    <title>New React App</title>
  </head>
  <body>
    <section id="dashboard"></section>
    <script src="dashboard.js"></script>
  </body>
</html>

Inside dashboard.js:

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

const MainDashboard = React.createClass({  
  render() {
    return (
    <div>
       <ul>
          <Link to="main">Main Dashboard</Link>
          <Link to="message">Message</Link>
          <Link to="calendar">Calendar</Link>
       </ul>

       {/* this is the important part */}:
       {this.props.children}

    </div>
   );
 }
});

const Message = React.createClass({/*...*/})
const Calendar = React.createClass({/*...*/})

ReactDOM.render((
  <Router>
    <Route path="/" component={MainDashboard}>
      <Route path="message" component={Message} />
      <Route path="calendar" component={Calendar} />
    </Route>
  </Router>
), document.body)

Notice the <Route path="/" component={MainDashboard}>? Even though you are accessing http://your-url.com/dashboard, React-router will know that you're at the root since that is handled by Django.

Now when a user navigates to the Message section on your Dashboard or tries to access it directly by entering http://your-url.com/dashboard/#/message, React-router will be able to handle that by rendering your Message component accordingly to your code.

For advanced usage, I suggest reading the documentation for react-router at https://github.com/reactjs/react-router/tree/master/docs

Happy coding!

Kenny Pham

Read more posts by this author.