Since you want to use React with Django templates, I assume that React code will only affect specific parts of your page. Based on this assumption, the following explanations are written.
First of all, you do not need to put all the JS code in the template - in fact it will be a mess.
You can create a separate JS-based build process using Webpack ( check out this method ). This improves your client-side code capabilities by allowing you to use CommonJS modules in a browser that you can directly extract from npm, including React .
Webpack, in turn, will generate a package (or several packages, depending on the nature of your application and Webpack configuration) that you will need to include in your Django templates using <script> tags, as usual.
Now you need to make a call to React.render() to make your React application somewhere in the existing page layout. You will need to use an empty HTML element with a specific id / class name as the mount point for the application.
But there is a caveat: you cannot access CommonJS modules directly from browser or Django templates. So either you
- output
React and your application to the window object or - create a module with glue code to handle application initialization and set this method for the
window object.
In any case, you will need to call the initialization code directly from the templates (check the glue code example , and the call to initialize the application ).
This initialization step also allows you to pass the variables available in Django templates into JS code.
The last Django template will look something like this:
{% load staticfiles %} {% extends 'base.html' %} {% block scripts %} <script type="text/javascript" src="{% static 'path/to/app.bundle.js' %}"></script> <script type="text/javascript"> </script> {% endblock %} {% block content %} <div class="app-mountpoint" /> {% endblock %}
And glue code:
var React = require('react'); var MyAppComponent = require('MyAppComponent'); window.MyApp = { init: function (opts) { var mountPoint = document.querySelector(opts.el); React.render(<MyAppComponent />, mountPoint); } };
I know that all this may seem overwhelming at the beginning (even more compared to the few steps that you had with Angular), but believe me, it will pay off in the end.
So to summarize:
- Writing React Code in Separate JS Files
- Use Webpack (using CommonJS modules) to link React code
- Include package in your django templates
- Change React code with glue code in Django templates