As I promised in my last article, I will explain how you can setup ReactJS with Django today. ReactJS is a best combination with Django. ReactJS takes care of frontend and Django takes care of Backend of your Website or User Interface.
Before you begin, I assume you have Django installed and setup till HTML rendering. If not, please read through “How to Install and configure Django to render HTML Template in 3 steps” .
Step1: Install and Setup NPM:
Let’s start by installing NPM . NPM is a package manager of javascript modules. NPM is distributed with Node.Js , so when we install Node.Js we get the NPM installed. So Let’s install LTS version of Node.js.
curl -sL https://deb.nodesource.com/setup_8.x | sudo bash - #It downloads PPA for latest LTS version of nodejs sudo apt install nodejs
Verify NPM is installed by checking it’s version.
vagrant@ubuntu-xenial:~/easyaslinux$ npm -v 6.4.1
Now you have NPM installed. Let’s go to root of the project directory and create a file called package.json and add the following content.
{ "name": "easyaslinux", "version": "1.0.0" }
package.json is something like requirements.txt of python where you store all necessary packages for your project. If you have package.json from any existing project, you can install all packages of that project by just copy/paste the package.json to your working directory and running command npm install .
Doing a ls on the root of the project directory would look like this. Here easyaslinux is my project name from last article.
vagrant@ubuntu-xenial:~/easyaslinux$ ls db.sqlite3 easyaslinux manage.py package.json README.md requirements.txt
Step2: Install Necessary JS packages using NPM:
Let’s install the necessary packages required to setup our ReactJS as Dev dependency.
npm install --save-dev react babel-core babel-loader@7 babel-preset-env babel-preset-react webpack webpack-bundle-tracker webpack-cli
If you are checking your package.json file now, you will see following lines added.
"devDependencies": { "babel-core": "^6.26.3", "babel-loader": "^7.1.5", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.24.1", "react": "^16.6.3", "webpack": "^4.26.1", "webpack-bundle-tracker": "^0.4.2-beta", "webpack-cli": "^3.1.2" }
Let’s install react-dom module as a dependency, this module is required to render your ReactJS code.
npm install --save react-dom
After this, You would see following lines added in the package.json file.
"dependencies": { "react-dom": "^16.6.3" }
Let me try to explain each package:
react and react-dom – react package is needed to process react components that we write and react-dom generates DOM-specific methods.
webpack – It is a module bundler which generates bundle of browser friendly files such as JS, CSS and Images from the ReactJS code that we write.
webpack-bundle-tracker – This package generate a JSON file (webpack-stats.json) which links Django to the bundle that is generated using webpack module.
webpack-cli – This package is required to run webpack command in command line.
babel-core – It is a dependent package of babel-loader and usually get installed when you install babel-loader.
babel-loader – This package allows transpiling JavaScript files using Babel and webpack.
babel-preset-env – This package compile Javascript ES6 code(any latest JavaScript code) to ES5.
babel-preset-react – This package compile JSX code to Java Scripts.
Once you installed above packages, you would see a new directory node_modules got created, which contains all the packages installed.
Tip: If you are facing issues while installing modules, just copy below content to your package.json and execute npm install .
{ "name": "easyaslinux", "version": "1.0.0", "devDependencies": { "babel-core": "^6.26.3", "babel-loader": "^7.1.5", "babel-preset-env": "^1.7.0", "babel-preset-react": "^6.24.1", "react": "^16.6.3", "webpack": "^4.26.1", "webpack-bundle-tracker": "^0.4.2-beta", "webpack-cli": "^3.1.2" }, "dependencies": { "react-dom": "^16.6.3" } }
Step3: Configure Webpack for ReactJS:
Now we have all necessary modules installed for ReactJS to work. Let’s configure ReactJS also. We need to create a static directory static from where our Django server will look for static contents like JavaScripts, CSS and Images.
mkdir -p easyaslinux/static
We need a place to store the ReactJS code that we write. Go to root directory of the project and create a directory reactjs and directory app under it.
mkdir -p reactjs/app/
Let’s touch a JSX file myapp.jsx for now. There is where we write our ReactJS code. I will explain this soon.
touch reactjs/app/myapp.jsx
Create webpack.config.js in the root of your project directory and add following content.
var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry:{ myapp: './reactjs/app/myapp' }, output: { path: path.resolve('./easyaslinux/static/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] } ] }, resolve: { extensions: ['*', '.js', '.jsx'] } };
webpack.config.js is a configuration file used for webpack bundle generation. We need to specify this config file along with webpack command in-order to generate the bundles. If you go through the webpack.config.js file, you can see that location of the ReactJS code and bundles to be generated is mentioned inside keys entry and output respectively.
Here webpack-stats.json act as bundle tracker which means Django checks this file to find the bundles.
Step4: Configure Babel for ReactJS:
As I mentioned Babel is module which transpiles whatever code syntax we write to browser supporting JS scripts. Webpack Bundle we generate contains these JS scripts. For this, let’s create a file called .babelrc in the root directory of your project and add following content.
{ "presets": [ "babel-preset-env", "react" ] }
I have given a small description on Babel modules in the step2.
Step5: Setup Django for ReactJS:
We have ReactJS all setup for Django. Now let’s setup Django for ReactJS. Let’s start by installing module django-webpack-loader which is required to load webpack bundles.
pip install django-webpack-loader
Once installed, open settings.py file edit/add following content.
INSTALLED_APPS = [ ......, ......, ......, 'webpack_loader' ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'easyaslinux/static'), ]
Note: Hope you already know easyaslinux is my Django project name.
We tell Django about the new module installed by mentioning it as a new app webpack_loader in INSTALLED_APPS list. Location of webpack bundles and webpack-stats.json is given in WEBPACK_LOADER dictionary. easyaslinux/static is declared as static directory so that Django will check in this directory for BUNDLE_DIR_NAME directories.
Let’s finish our Django integration by making a small change in the Django template Sample_html.html .
{% extends "base.html" %} {% load render_bundle from webpack_loader %} #added {% block main %} <div id="myapp"></div> #added {% render_bundle 'myapp' %} #Added {% endblock %}
For simplification, whatever Reactjs code we write in myapp.jsx will replace the DOM object <div id=”myapp”></div> in the HTML template. If you would like to learn how template works in Django, go here >>
Now let’s write myapp.jsx to display something.
Step6: Write first ReactJS code:
We integrated Django to ReactJS. It is time to write our first ReactJS code. I hope you remember a file we touched in step3 at reactjs/app/myapp.jsx . Open this file and add below content.
As a side note, It is recommended to write ReactJS code in JSX format which is basically a powerful template language.
import React from 'react' import ReactDOM from 'react-dom' function Demo() { return <h1>Hello from EasyAsLinux.com through ReactJS</h1>; } const element = <Demo/>; ReactDOM.render( element, document.getElementById('myapp') );
This JSX code prints “Hello from EasyAsLinux.com through ReactJS” on your browser. This code is pretty straight forward. We created a function which returns a HTML header tag and the function is used as component <Demo/> . The output of the component is given to DOM object myapp with help of react-dom module.
If you are new to ReactJS, do some ice breaking learning at here >>
Step7: Let’s generate Bundles – ReactJS + Django:
We have all setup. Let’s generate the static bundle and see our final output on the browser. Go to root of your project directory and run the webpack command.
vagrant@ubuntu-xenial:~/easyaslinux$ ./node_modules/.bin/webpack --config webpack.config.js Hash: 6fedded46f9d29b0cbf3 Version: webpack 4.26.1 Time: 1086ms Built at: 2018-12-08 08:14:15 Asset Size Chunks Chunk Names myapp-6fedded46f9d29b0cbf3.js 109 KiB 0 [emitted] myapp Entrypoint myapp = myapp-6fedded46f9d29b0cbf3.js [2] ./reactjs/app/myapp.js 544 bytes {0} [built] + 7 hidden modules
Success, bundles got generated. If you are going to the bundles directory, you would see a JS file generated.
vagrant@ubuntu-xenial:~/easyaslinux$ ls easyaslinux/static/bundles/ myapp-6fedded46f9d29b0cbf3.js
Each time you run the webpack command, new JS bundle file is generated with a random name and webpack-stats.json tells Django the new name of the bundle . Just openwebpack-stats.json, it would look like this.
vagrant@ubuntu-xenial:~/easyaslinux$ cat webpack-stats.json {"status":"done","chunks":{"myapp":[{"name":"myapp-6fedded46f9d29b0cbf3.js","path":"/home/vagrant/easyaslinux/easyaslinux/static/bundles/myapp-6fedded46f9d29b0cbf3.js"}]}}
We have created a lot of files and directories. Just for reference, see directories in my project directory.
vagrant@ubuntu-xenial:~/easyaslinux$ tree -L 1 . ├── db.sqlite3 ├── easyaslinux ├── manage.py ├── node_modules ├── package.json ├── package-lock.json ├── reactjs ├── README.md ├── requirements.txt ├── webpack.config.js └── webpack-stats.json 3 directories, 8 files
Let’s run the Django server.
vagrant@ubuntu-xenial:~/easyaslinux$ ./manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. December 08, 2018 - 08:22:46 Django version 1.9.3, using settings 'easyaslinux.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C.
and check your browser.
Hurray, you have completed the tutorial. Now start writing your ReactJS app in newapp.jsx and have Django to power it up. I will be writing a new article on creating a simple React App with Django.
Subscribe to this blog so that you don’t miss out anything useful (Checkout Right Sidebar for the Subscription Form) . Please also put your thought on this article as comments .