ReactJS + Django Framework

The Perfect Match: How to Integrate ReactJS with Django Framework for Stunning Web Apps

DevSumitG
5 min readApr 27, 2023

--

ReactJS is a popular JavaScript library used for building user interfaces, while Django is a high-level Python web framework that is widely used for building web applications. Connecting these two powerful tools can produce a robust web application.

In this tutorial, We will walk through the steps to connect ReactJS and Django Framework using A Hello World! application.

Prerequisites

Before getting started, You should have some basic knowledge of ReactJS and Django Framework. You should also have Node.js and Python installed on your machine.

[Note: Use Virtual Environment For Good.]

Steps

Step 1: Create a New Django Project and a New React Application

The first step is to create a new Django project and a new React application.

You can create the Django project using the following command:

django-admin startproject myproject

This will create a new directory called myproject with the basic structure of a Django project.

Next, you can create a new React application using the following command:

npx create-react-app myapp

Step 2: Install Required Packages

Once the project and application are created, we need to install some packages. For Django, we need to install Django Rest Framework and Django Cors Headers. For React, we need to install Axios for making HTTP requests.

To install Django Rest Framework and Django Cors Headers, run the following command:

pip install djangorestframework django-cors-headers

To install Axios, run the following command inside the myappdirectory:

npm install axios

Step 3: Build the API Endpoints in Django

After installing the required packages, we can start building the API endpoints in Django. We will create a new Django app to handle the API requests. The API endpoint will return JSON data when we make HTTP requests to it. We can use Django Rest Framework to build the API endpoints.

To create a new Django app, run the following command inside the myproject directory:

python manage.py startapp myapi

This will create a new directory called myapi with the basic structure of a Django app.

Next, Open the settings.py file inside the myproject directory and add the following lines of code:

INSTALLED_APPS = [
# ...
# 👇 Add here your installed app's
'rest_framework',
'corsheaders',
'myapi',
]

MIDDLEWARE = [
# ...
# 👇 Add this line here
'corsheaders.middleware.CorsMiddleware',
# Add above line just before this line 👇
'django.middleware.common.CommonMiddleware',
]

# 👇 Add this line here
CORS_ORIGIN_ALLOW_ALL = True

These lines of code will add the rest_framework, corsheaders, and myapi apps to the INSTALLED_APPS list, add the CorsMiddleware to the MIDDLEWARE list, and allow all origins to make cross-origin requests.

What is Handling Cross-Origin Resource Sharing (CORS)?

When we try to make an HTTP request from a different origin (e.g., from the React app to the Django API), we may run into a CORS error. To fix this, we need to add the Django Cors Headers package to our Django project. This package will add the necessary headers to allow cross-origin requests.

Next, open the views.py file inside the myapi directory and add the following lines of code:

from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def hello_world(request):
return Response({'message': 'Hello, world!'})

This code defines a new API endpoint that returns a JSON response with the message “Hello, world!”.

Add URLs :

Open the urls.py inside the myproject directory and add these lines:

from django.contrib import admin
from django.urls import path, include # 👈 Add include here

urlpatterns = [
path('admin/', admin.site.urls),
# 👇 add your myapi app urls path here
path('api/', include('myapi.urls'))
]

Finally, Create the urls.py file inside the myapi directory and add the following lines of code:

from django.urls import path
from . import views

urlpatterns = [
path('hello-world/', views.hello_world, name='hello_world'),
]

This code defines a new URL pattern that maps to the hello_world function in views.py.

Step 4: Create a React Component to Make HTTP Requests

Next, We need to create a React component that makes HTTP requests to the API endpoints. We will use Axios to make the HTTP requests. Once we receive the JSON data, we can display it on the web page using React components.

Create a new file called HelloWorld.js inside the src directory of the myapp directory, and add the following lines of code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function HelloWorld() {
const [message, setMessage] = useState('');

useEffect(() => {
axios.get('http://localhost:8000/api/hello-world/')
.then(response => {
setMessage(response.data.message);
})
.catch(error => {
console.log(error);
});
}, []);

return (
<div>
<h1>Hello, World!</h1>
<p>{message}</p>
</div>
);
}

export default HelloWorld;

This code defines a new React component called HelloWorld that makes an HTTP GET request to the hello-world API endpoint we defined earlier. The response data is stored in the message state, which is displayed on the web page.

Step 5: Render the React Component

Finally, we need to render the HelloWorld component inside the App.js file in the src directory of the myapp directory. Replace the contents of App.js with the following lines of code:

import React from 'react';
import HelloWorld from './HelloWorld';

function App() {
return (
<div>
<HelloWorld />
</div>
);
}

export default App;

This code renders the HelloWorld component inside the div element with the root ID.

Step 6: Run the Project

To run the project, open two terminal windows.

In the first window, navigate to the myproject directory and run the following command:

python manage.py runserver

This will start the Django development server.

In the second window, navigate to the myapp directory and run the following command:

npm start

This will start the React development server.

Open your web browser and navigate to http://localhost:3000/. You should see the message "Hello, world!" displayed on the web page.

Result,

Output, Hello World!

Conclusion

Connecting ReactJS and Django Framework can be a powerful combination for building web applications. By following the steps outlined in this tutorial, you can connect these two tools and build a robust web application. Remember to install the required packages and handle CORS errors to ensure smooth communication between the React app and the Django API.

There are many tutorials and resources available online to help you get started with connecting ReactJS and Django Framework. It’s important to carefully follow the steps and ensure that all required packages are installed. Additionally, be sure to handle CORS errors to avoid any issues with cross-origin requests. With these considerations in mind, you can confidently connect these two powerful tools and build a robust web application.

That’s it! You have created a Hello World! application using ReactJS(Frontend) + Django Framework(Backend).

Happy coding!

Thank you for taking the time to read this blog about How to Integrate ReactJS with Django Framework. I hope that you found the information presented here useful and informative.

If you have any questions or comments about the information presented in this blog, please feel free to reach out. Thank you again for reading!

Support my passion for sharing development knowledge by making a donation to Buy Me a Coffee. Your contribution helps me create valuable content and resources. Thank you for your support!

Resources

--

--