Design a site like this with WordPress.com
Get started

Serve React From Django in 10 mins

In this tutorial we will go through integration of django and react in just 10 min

There aren’t many tutorials clearly identifying changes required in django app to run with a react app. Most tutorials seem complex and steps mentioned are often are not necessary. We will look at steps to integrate django rest service with a react web application and all this will be served from the django project. We will also demonstrate hot deployment of react changes when working in django when we are developing and there are constant changes that we would want to make to the UI pages and look at result of those changes. You wont believe, it hardly takes 10 mins.

I am making a few assumptions here.

  1. Django is installed
  2. DjangoRestFramework is installed
  3. Basic understanding of Django
  4. npm and npx are installed
  5. PyCharm IDE – Not mandatory but recommended

The above installations are fairly simple and extremely easy. We wont go into details of those installations as you would find bunch of those on google search

The code for this project is present @ https://github.com/letsblogcontent/Python/tree/master/DjangoReactProject

Steps

Step 1Create Project

Lets begin by creating a django project. As you can see below, I have created a new django project “DjangoReactProject

If you open the directory, you should find below files/directories created by django

Step 2Create App

Next up we are going to create a new Django app, lets call this as service as we are going to serve rest calls from this service.

Step 3Register the app & Create url mapping

I have opened my project in pycharm but you may as well edit the files in any editor.
The current project structure should look like

Next is to register the service app to the project, this is done by adding the app config in the settings.py file of the project.

Now that we have registered our app to the project. Lets add a function in the views.py file of our app. This function is what we will respond from the service app for our project. If you see below In the views.py file, I have added a new function which responds with a dummy json string having name and city attributes.

Next, Create a urls.py file in the our service app and create a mapping between a default http request with the function we have created just now.

Step 4 – Test the url

Now lets run our project to see if we receive response for our mapped url. Run the command “python manage.py runserver” and you should see below console output.

Now navigate to the url http://localhost:8000/api” to see below ouput on your browser.

Step 5 – Create a React App with npx

Lets create a react app inside our project folder with npx. This should take a few mins. This will download all the packages required for react. Once this is complete, You should see directory structure like below

Steps 6 – Add Component and Update App.js

Lets create a new directory named “components” under src in our react app just created and create a new file “MyComponent.js” and add below content .

This is a very basic code in React and most of you must already understand what is going on here.

We have created a new React component and initialized state of the component with name and city. In the render function, we are passing an html with the content of the state inside a div element. We have overriden the component “componentDidMount” in which we are making an http request to the url we created in Django and setting it into the state of the component

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {
    constructor(){
       super();

        this.state = {
            name: null,
            city: null
        };
    }

    componentDidMount(){
        fetch('/api/')
         .then(response => response.json()
         .then(data => {
                            this.setState({ name : data.name });
                            this.setState({ city: data.city });
                        }
               ));
    }

    render() {
       return (
       <div>
       <div> {this.state.name} </div>
       <div> {this.state.city}  </div>
       </div>
       );
    }
}

export default MyComponent;

Now lets add this component to App.js file in the react application under the src folder. React must have pre-populated some content. Remove all of that and copy below code to the App.js file

import React from 'react';
import logo from './logo.svg';
import './App.css';
import MyComponent from './components/MyComponent.js'

function App() {

  return (
    <div className="App">
      <h1>React App - Served from Django</h1>
      <MyComponent/>
    </div>
  );
}

export default App;

Step 7 Run the react build

Navigate to the react app folder and create react build by running npm run build. A build directory will be created after successful execution of the build with all the files required for the react app. The starting point of the application being index.html

Step 8 – Configure Django to serve react build

We now just need to point Django to the build directory of react so that it starts serving from there.
In our DjangoReactProject directory present in the root of our project, navigate to settings.py

Find Templates in the settings.py file and add the build directory of our react application as show in the screenshot in the DIRS. We are telling python where to find templates in the react application

In the same file add a new variable “STATICFILES_DIRS” if not present already and add variable which points to the static content of the react app as below

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'webapp/build/static')]

In the urls.py file of the DjangoReactProject include below path in the urlpattern and import TemplateView to render index.html from our react app

from django.views.generic import TemplateView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('service.urls')),
    path('', TemplateView.as_view(template_name='index.html'))
]

Now run our django server and it should start serving our react application and call the rest service /api to render the response

 C:\DjangoReactProject>python manage.py runserver

This should deploy our django app with react @ http://localhost:8000/. Navigate to the url to see below page.

Step 9 – Hot Deployment

So the above is fine structure to deploy our react application once all of our react code is ready, but during development it is going to be very difficult to always having to build our react app for small changes in our react app. So to overcome this, we have to make a small change in the react app so that when we are developing all the requests are redirected to django app.

So when we are developing we will run the inbuild react server to server our react application, which will redirect calls to django server when required.

To configure this we just need to add proxy configure in the package.json file of the react app.

Here we have given the address of server

"proxy": "http://127.0.0.1:8000",

Once this is done, lets run the react server by running command “npm run start”. This will start the react application @ http://localhost:3000/ and you should see the below page. Any changes to react will be hot deployed for development.

At this point any changes in the Django or the react app are hot deployed and we can make changes to quickly see the results.

Ohh. We have still not reached Step 10, that was really easy. Let us know if you have any queries or like the page if you have like this tutorial, post any feedback if you have. Thank you!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: