Integrating React and Django (Part 1)
March 7, 2019, 10:26 p.m.
| Written By: Tanner S.
1200px-React-icon.svg.png

Django can be a great system to serve both the front and back end of your website. However, its strength is typically in the back end and database capabilities. There are so many great front end frameworks, that sometimes it is good to branch out on what you use on the front end, including React. It makes it very easy to collaborate with front end developers, because you can have the front end and the back end working completely separately, so the front end can just work on the front end without having to touch Django.

React is a front end javascript framework that creates Single Page Applications (SPAs). That means that all of your website content is rendered at once, and any changes in your url will just activate different functions in Javascript and display different things, without having to access a server to render the page.

Note: This assumes you have worked with both React and Django, at least separately.

Overview

We will be using Django to create the backend of our project, and React will serve the front end files. So, we will do this by building an API with Django, which will allow us to perform requests on the front end with React. As we said, the front end will not need to touch Django. Whoever is working on the front end will just need to know the API endpoints that you built with Django.

So, let's look how to do this.

Getting Django Ready

This is going to be your preference. Pick where you want to put your project and go to that directory in your command prompt.

Then, run the following:

C:\Users\Tanner\Documents> mkdir project-folder && cd project-folder
C:\Users\Tanner\Documents\project-folder>

Your command prompt should look like the above. You are in your main project directory. Let's create a virtual environment (you can skip this if you already know enough about setting up virtual environments).

C:\Users\Tanner\Documents\project-folder> virtualenv env

You will see all of the installations and then it will be created. Next, do the following commands:

C:\Users\Tanner\Documents\project-folder> env\scripts\activate
(env) C:\Users\Tanner\Documents\project-folder> pip install django

This will install Django in your virtual environment. Feel free to specify another version of Django. Next, let's install Django Rest Framework (DRF). DRF is a widely used Django library you use to build your own APIs.

(env) C:\Users\Tanner\Documents\project-folder> pip install djangorestframework

Now, let's create our project:

(env) C:\Users\Tanner\Documents\project-folder> django-admin startproject myapiproject

So far, we have just created a Django project within our project-folder with a virtual environment and installed django and djangorestframework. It should still be activated. Our project structure should be the following:

project-folder/
    env/
    myapiproject/

Nothing too crazy here. If you have worked with Django and virtual environments before, this should be pretty straightforward. We will now need to add DRF in our INSTALLED_APPS by doing the following in our settings.py (this is just from their documentation):

INSTALLED_APPS = (
    ...
    'rest_framework',
)

This is all we need to just set up our back end. Now, let's move onto the front end.

Setting Up React

So far, we have set up our backend and virtual environment. However, where does the front end go in all of this? I will make it in the same parent-directory, but outside of our back end. I have seen different implementations of this, where they put the React project within the Django project so it is in the same directory as a Django app would be. However, I dislike this because I want to keep the front end and back ends as separate as possible.

So, let's jump right into it. First, open up another command prompt and go to the project-folder.

NOTE: We are in a separate command prompt, so we therefore do not have the virtual environment activated.

Then, do the following:

C:\Users\Tanner\Documents\project-folder> create-react-app myapiproject_ui

Using create-react-app, we can easily create a React project. After running this command, your project structure should look like the following:

project-folder/
    env/
    myapiproject/
        myapiproject/
            settings.py
            urls.py
            wsgi.py
        manage.py
    myapiproject_ui/
        node_modules/
        package-lock.json
        package.json
        public/
        README.md
        src/

We have completely separate sub directories for our back end and front end, without commingling them at all by doing something like putting the UI in our Django project. The holdback is that you will theoretically have two deployments: one for your UI and the other for your django project. Your React UI will be a static deployment, where you will deploy the index.html to a server when you do npm run build. Then, you will deploy your Django project separately (at least that's how I would do it).

We have officially set up our front end and our back end. Now, let's integrate them.

Integrating React with Django

We have finally reached the main event. In order to set it up, let's make sure we know how React and Django actually works.

When you are building a project with React, you can use npm run start to get a live version of the changes you are making at localhost:3000. However, this is not how it works in production. In production, you will use npm run build, which will create an index.html file that will hold essentially all your code.

When you are building a project in Django, you will use python manage.py runserver to start the server locally while you are in development, at localhost:8000.

So, the idea is the following: your API endpoints for your React project will be localhost:8000 during development. I typically have two command prompts open: one that will run the Django development server via python manage.py runserver, and another that will run the development environment for React that will update as you make changes, via npm run start.

Let's jump into it.

In React, I use the axios package to work with API endpoints.

If you want to use this package, in your React terminal, do the following:

C:\Users\Tanner\Documents\project-folder\myapiproject_ui> npm install axios --save-dev

How do we reference the API endpoint efficiently? In the myapiproject_ui\src, create a file called env.js. This is where all of the environment variables can go, including the base api endpoint.

Then, you can easily change the base api endpoint when you deploy and if you ever switch your domain.

The env.js file will have the following:

var Data = {
    "baseAPIEndpoint":"http://localhost:8000"
};
export default Data;

Then, whenever we need to reference the baseAPIEndpoint, we can do the following:

import Data from "./env.js";
...
<a href={Data.baseAPIEndpoint+"/endpoint"}>Link</a>

Conclusion

Please note that this is just one example of a workflow using React and Django. Many people do use the method of serving most of the template files from the index.html that is created via npm run build, and do the entire UI within your Django directory. However, this is a way I like to in order to keep your front end and back end as modular and separate as possible.