Integrate React#
This page explains how to integrate React in your Django project.
👉 New to App-Generator? Join our 10k+ Community using GitHub One-Click SignIN.
React is one of the most popular front-end frameworks, known for its flexibility in creating dynamic user interfaces. Integrating it with Django, a robust back-end framework, can lead to a powerful full-stack application setup with a single codebase. This guide walks you through integrating a React page into Django using Webpack, simplifying both development and deployment.
Project Setup#
To get started, let’s create a Django project and add a new app that will host our React frontend. Open your terminal and follow these steps.
Clone the project: First, set up the Django project by cloning it from a Git repository.
git clone -b base https://github.com/app-generator/docs-django-drf.git cd docs-django-drf
Create a Virtual Environment: Inside the cloned directory, create a virtual environment to manage Python dependencies.
python3 -m venv venv source venv/bin/activate
Install Django Dependencies: With the virtual environment active, install Django and other required packages.
pip install -r requirements.txt
With Django set up, we can now proceed to integrate React using Webpack.
Setting Up React with Webpack#
To serve a React component from Django, we’ll set up Webpack as our JavaScript bundler. This setup enables Django to serve the static files generated by React, making it possible to develop both the back end and front end in the same project.
### Why Use Webpack?
Webpack is a powerful tool for bundling JavaScript and other assets, especially for larger applications with complex front ends like React. It transforms and optimizes code into small, manageable files and helps improve the loading speed by bundling and compressing resources. Webpack also allows for live reloading in development, meaning it rebuilds assets whenever changes are made.
Step 1: Set Up the Django Project#
Create a new directory called frontend: Inside your Django project directory, create a new directory named
frontend
to host the React files.mkdir frontend/src/
Configure Django Settings: Open
settings.py
in your Django project and configure theSTATICFILES_DIRS
setting to include the static files for the frontend.STATICFILES_DIRS = [ BASE_DIR / "frontend/static", ]
Step 2: Create React and Webpack Files#
Create Frontend Directories: Inside the
frontend
app, create the necessary directories for your React setup:mkdir -p frontend/static/frontend mkdir -p templates/templates/frontend
Initialize NPM and Install Dependencies: Initialize a new npm project and install React, Webpack, and Babel.
npm init -y npm install react react-dom npm install --save-dev webpack webpack-cli webpack-bundle-tracker @babel/core @babel/preset-env @babel/preset-react babel-loader
Create Webpack Configuration: Create a file named
webpack.config.js
with the following content to define Webpack settings:const path = require("path"); const BundleTracker = require("webpack-bundle-tracker"); module.exports = { entry: "fronted/src/index.js", output: { path: path.resolve("frontend/static/frontend/"), filename: "main.bundle.js", publicPath: "/static/frontend/", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env", "@babel/preset-react"], }, }, }, ], }, plugins: [ new BundleTracker({ filename: "./webpack-stats.json" }), ], mode: "development", };
Configure Babel: Add a
.babelrc
file infrontend/static/frontend
to define presets for Babel:{ "presets": ["@babel/preset-env", "@babel/preset-react"] }
Why Babel? Babel enables you to use the latest JavaScript syntax (ES6+) in your React app and transpile it into JavaScript that all browsers can understand. This is essential for compatibility, as not all browsers natively support the latest JavaScript features used by React.
Create React App Files: Inside
frontend/src/
, create asrc
directory with two files:index.js
.// frontend/src/index.js import React from "react"; import ReactDOM from "react-dom/client"; export default function App() { return ( <div> <h1>This is a react Application</h1> </div> ); } const root = ReactDOM.createRoot(document.getElementById("app")); root.render(<App />);
Build the React App: Run Webpack to build the React files:
npm run dev
This command tells Webpack to bundle your React code into a single file (main.bundle.js
) in the frontend/static/frontend
directory, making it easy for Django to serve it as a static file.
Step 3: Configure Django to Use Webpack Files#
To render the Webpack bundle in Django, we need to use django-webpack-loader
, which integrates Django with Webpack bundles by tracking the output files.
### Why Use django-webpack-loader
?
django-webpack-loader
reads the webpack-stats.json
file generated by Webpack to dynamically include the bundled JavaScript files in Django templates. This is useful because it allows Django to reference the latest bundle file each time Webpack rebuilds, eliminating the need for hardcoded paths in templates.
Install
django-webpack-loader
: Installdjango-webpack-loader
in the root of your Django project:pip install django-webpack-loader
Add
webpack_loader
toINSTALLED_APPS
: Addwebpack_loader
toINSTALLED_APPS
insettings.py
and configure it to point towebpack-stats.json
:INSTALLED_APPS = [ ... 'webpack_loader', ... ] WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'frontend/', # Location of bundled files 'STATS_FILE': BASE_DIR / 'webpack-stats.json', } }
Create a Django Template for React: In
templates/frontend
, createindex.html
to render the React component:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>React in Django</title> {% load render_bundle from webpack_loader %} {% render_bundle 'frontend' %} </head> <body> <div id="react-root"></div> </body> </html>
Here, {% render_bundle 'frontend' %}
dynamically includes the JavaScript bundle in the template, allowing the React component to render.
Step 4: Set Up Django View and URLs#
To display the React page, set up a Django view and URL configuration.
Create a Django View: In
home/views.py
, create a view to render the template:# home/views.py from django.shortcuts import render def frontend(request): return render(request, 'frontend/index.html')
Add URL Configuration: In
home/urls.py
, add a URL pattern for the view:# home/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('frontend', views.frontend, name='frontend'), ]
Step 5: Run the Project#
Run Webpack in Development Mode: At the root of the project, run:
npm run dev
This will automatically rebuild the bundle when files are modified.
Run the Django Server: In a new terminal window, start the Django server:
python manage.py runserver
Test the Setup: Visit http://127.0.0.1:8000/frontend/ in your browser. You should see:
Hello from React! This is a React component rendered in Django.
Conclusion#
In this guide, we set up a simple React page within a Django project using Webpack to bundle and serve React as static files. This setup combines Django’s backend power with React’s front-end capabilities, creating a flexible and efficient development environment for full-stack applications.
You can find the code for the project here app-generator/docs-django-react
Links#
👉 New to App-Generator? Join our 10k+ Community using GitHub One-Click SignIN.
👉
Download
products and start fast a new project👉 Bootstrap your startUp, MVP or Legacy project with a custom development sprint