Connecting React Frontend with Django Backend: A Step-by-Step Guide
Table of contents
This guide will walk you through the process of setting up a React frontend that communicates with a Django backend in the most simplest and the minimum possible way. Let's get right in..
Frontend Setup
Initialize the Frontend Project: Start by creating a new React project using Vite, a next-generation frontend tooling. Run the following commands in your terminal:
npm create vite@latest frontend -- --template react cd frontend npm install && npm install axios react-router-dom
API Configuration: Create a file named
api.js
inside thesrc
directory to manage API requests to the Django backend. We will use axios package in react which will help us in connecting react with django:// src/api.js import axios from 'axios'; const api = axios.create({ baseURL: 'http://127.0.0.1:8000', // Django backend URL }); export default api;
Create Home Component: Add a new file named
Home.jsx
inside thesrc
directory with the following code:import { useState, useEffect } from "react"; import api from "../api"; import './App.css' const Home = () => { const [data, setData] = useState(null); useEffect(() => { api.get('/users/') .then(res => setData(res.data)) .catch(err => console.log(err)); }, []); return ( <> <h1>Home</h1> {JSON.stringify(data)} </> ); }; export default Home;
App Configuration: Update
App.jsx
to include routing and render theHome
component:// src/App.jsx import { BrowserRouter, Routes, Route } from 'react-router-dom'; import Home from './Home'; function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> </Routes> </BrowserRouter> ); } export default App;
Backend Setup
Initialize the Backend Project:Open a new terminal move one dir back from the frontend dir. Create a new Django project and an app for handling user data:
django-admin startproject backend cd backend python3 manage.py startapp users
Define Views and URLs: In
views.py
of theusers
app, define a simple view to return JSON response:# users/views.py from django.http import JsonResponse def home(request): return JsonResponse({"message": "React-Django app connected successfully"})
Update
backend/urls.py
to include the view:# users/urls.py from django.urls import path from users.views import home urlpatterns = [ path('users/', home, name='users'), ]
CORS Configuration: Install
django-cors-headers
and configure it insettings.py
to allow cross-origin requests:pip install django-cors-headers
Update
settings.py
:INSTALLED_APPS = [ ... 'corsheaders', 'users', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True
Database Migration: Apply migrations to create necessary database tables:
python3 manage.py migrate
Run the Application
Start Development Servers: Start both frontend and backend servers:
npm run dev # Start React development server
python3 manage.py runserver # Start Django development server
Access Application: Open browser and navigate to
http://localhost:
5173
to view your React frontend. You can now interact with your application, and the React frontend will communicate with the Django backend seamlessly.
By following these steps, you've successfully connected your React frontend with a Django backend, paving the way for you to build much complex and scalable web applications.
Happy coding!