How to Integrate Django With React in 2023?

In the world of modern web development, making interactive and dynamic websites is a big deal. One popular way to do this is by using two important tools: Django, which helps build the server-side of the website using Python, and React, which helps create the user interface using JavaScript.
In this blog, we’ll learn how to put these two together and make them work smoothly.
We’ll also tackle a technical challenge called CORS, which can sometimes create problems when Django and React try to talk to each other. We’ll use some special instructions, called headers, to ensure they can chat without issues.
By the end of this blog, you’ll know how to combine Django and React effectively and make them play nicely together to create awesome web experiences.
To read more about what is React, refer to our blog What is React? A Beginner’s Guide to JavaScript Library
Setting Up the Development Environment
Before we dive into the integration process, make sure you have the following tools installed:
- Python and pip (Python package manager)
- Node.js and npm (Node.js package manager)
Creating a Django Project
Let’s start by creating a new Django project:
$ pip install django
$ django-admin startproject myproject
$ cd myproject
Building a React Application
Inside the Django project directory, create a new directory for your React app:
$ npx create-react-app frontend
$ cd frontend
Integrating Django With React and CORS Headers
Setting Up Django for Cors
To handle CORS in Django, install the django-cors-headers package:
$ pip install django-cors-headers
Then, add it to your project’s settings:
# myproject/settings.py
INSTALLED_APPS = [
# ...
'corsheaders',
# ...
]
MIDDLEWARE = [
# ...
'corsheaders.middleware.CorsMiddleware',
# ...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000", # Add your React app's origin here
]
API Endpoints and Django Views
Create a sample API endpoint in your Django project:
# myproject/api/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
class SampleAPI(APIView):
def get(self, request):
data = {'message': 'Hello from Django API!'}
return Response(data)
Making CORS-Compatible API Requests in React
Install Axios and create a React component to fetch data from the Django API:
$ npm install axios
// frontend/src/components/DjangoData.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const DjangoData = () => {
const [data, setData] = useState('');
useEffect(() => {
axios.get('http://localhost:8000/api/sample/') // Adjust URL to your Django API endpoint
.then(response => {
setData(response.data.message);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);
return (
<div>
<p>{data}</p>
</div>
);
};
export default DjangoData;
Rendering React Components in Django Templates
Integrate the React component into a Django template:
// frontend/src/App.js
import React from 'react';
import ReactDOM from 'react-dom';
import DjangoData from './components/DjangoData';
ReactDOM.render(
<React.StrictMode>
<DjangoData />
</React.StrictMode>,
document.getElementById('root')
);
To read more about to set up a Django project, refer to our blog How to Set Up a Django Project in 10 Steps
Conclusion
In summary, integrating Django with React offers a potent blend of technologies for crafting contemporary web applications. Django, a Python-based web framework, furnishes a robust backend infrastructure for data management, server-side logic, and security. In contrast, React, a JavaScript library, excels at constructing responsive user interfaces replete with reusable components, enhancing the frontend’s usability and appeal. This fusion of Django’s backend prowess with React’s frontend agility empowers developers to create feature-rich, interactive web apps.
At the heart of this integration lies the establishment of seamless communication between the backend and frontend. This typically involves utilizing RESTful APIs or GraphQL to facilitate the exchange of data between the two layers. RESTful APIs enable developers to define endpoints within Django, which React components can then access to fetch and update data. Alternatively, GraphQL offers a more flexible data querying approach, allowing clients to request precisely the data they require.
To successfully integrate Django with React, one must follow a structured process. This includes crafting API endpoints in Django, employing asynchronous AJAX requests in React to retrieve and transmit data, and implementing robust authentication mechanisms to ensure application security. By maintaining organization, adhering to best practices, and prioritizing security, developers can ensure the smooth and secure operation of their integrated Django-React applications.