Adding React inside a Django project

I'm also doing the same thing right now - moving away from embedded HTML script tags into require land. Here is the tutorial I am following, and here is my file system so far. I am doing it in Node but it shouldn't be that different for a Django project as the React frontend code is decoupled from any backend other than API URL's.

Your node_modules folder contains react-bootstrap. In your myapp.js, use the require('react-bootstrap') to load up the library which is contained in your node_modules folder.

  1. Where should I put my React code to work with these npm modules (should I use var React = require('react')?

You can put the code anywhere. If your file system looks like this:

project/
  react/
    myapp.js
  node_modules/
    react source code
    react bootstrap stuff

Then you can just do var React = require('react'); in myapp.js.

  1. Do I need to compile this code somehow (using webpack?)

Yes, I would consult the webpack tutorial I linked earlier, it should explain how to compile all your React code into a single bundle.js. Here is also another good tutorial. This bundle.js file contains all the source code of your requires. So if your myapp.js looks something like

var React = require('react');
var ReactBootstrap = require('react-bootstrap');

then the bundle.js now contains all of the React and react-bootstrap javascript code, along with the myapp.js source code.

  1. How do I then integrate this with Django? Should I compile it all to myapp.js and just include that in my HTML template?

I've only done work on Nodejs, but my React code so far hasn't touched any Node code, and I don't think it will touch any Django code (again I've never done Django so I might be wrong). All you need to do is compile with webpack, which spits out a bundle.js. You put that bundle.js in your HTML and it'll load up myapp.js.

Tags:

Django

Reactjs