Integration a React app into Django project
03.08.2024
15.04.2025
7 minutes
125
0
0
0
0
Intoduction
In this article, I will show you how to integrate a React application into a Django project. The idea is that Django renders its templates, and React modifies them as needed.
If you want to skip the basic setup and move on to the React integration part. Also you can download a ready-made project for it.
Create a Django project
We will start by creating a root directory for our project.
Now, create and activate a virtual environment, for windows.
Commands for linux:
After activating a virtual environment, we have to install django package and start a new project. Let’s call it a Website.
If everything is done right, we will successfully launch a project. Just like that:
Create a Backend app
Now, we need to install a couple of new Python packages to configure our Backend app. These packages:
- django-cors-headers: for enabling so-called Cross-Origin Resource Sharing (CORS) for communication between React app and Django API.
- djangorestframework: a Django app that allows us to build an API for further use.
Install and configure our first Django app:
Edit the settings.py file using your favorite text editor. In my case, it is NeoVim. We will link the newly created app and those that we installed earlier.
Create an urls.py file for linux:
For windows machines:
Paste the next content in the urls.py file in the Website folder:
Here we imported routers for rest_framework and views from our Backend app and then included them into urlpatterns. The next thing we will do is to create a placeholder model for now. In the Backend/models.py file paste:
And link our model with the default Django admin app, in the Backend/admin.py file paste:
To work, the rest framework needs to have a serializer class. What he does is convert Django models into JSON files for us. Open(Create) a Backend/serializers.py file and paste next content:
The last thing we need to do is create a specific view class for BackendModel. Open the Backend/views.py file and add the next lines:
At the end, create all migrations and apply them, also create a super user to gain access to the database:
Create a Frontend app
It is time for the Frontend app. This app is going to contain our React app. But first, we need to create, link, and prepare this app. As always, nothing changed:
In the settings.py file, link it:
And in the Frontend/urls.py file, add the view:
And create a new view function in Frontend/views.py file:
To render something, we need to create an HTML file, and folder along the way too:
And include the created earlier Frontend/urls.py file in the Website/urls.py.
React installation
Now it is time for React installation. It is relatively easy if you know what to install ;). Go to the Frontend directory and create some directories:
At this step, the Frontend app is ready, and the last thing to do is to create and configure the React app. I hope you already have a npm.
Install initial packages, one by one:
- webpack to bundle all of our JS code
- babel for translating all of our JS and CSS code into friendly types for each browser.
- react for developing all of our frontend parts of the website
After installing the necessary packages, you need to configure Babel. Create a configuration file; name it babel.config.json. And paste the following configuration code:
Now let's set up the webpack package, but first let's create a configuration file. Name this file webpack.config.js. And insert the following configuration code:
Now, let's do a little magic in the package.json file. To be more specific, we'll add two scripts to manage npm:
Creating first react component
После того как мы всё настроили давай напишем немного react кода. В папке Frontend/src, создай файл index.js, а в папке Frontend/src/components, создай файл App.js. Теперь вставим временный код в созданный файл src/components/App.js:
After we have everything set up, let's write some react code. In the Frontend/src folder, create a file called index.js, and in the Frontend/src/components folder, create a file called App.js. Now paste the temporary code into the created file src/components/App.js:
We need to include the App component in src/index.js file. Paste this:
At the end, we need to paste this example code into the app.html file. His location is Frontend/templates/Frontend/app.html.
Everything is set up. Now let's test it. First, start the Django server, then the webpack server using the script you created earlier:
If you did all right, you will see something like this.

Conclusion
All begins with Django’s rendered template. After this, React is going to find a div by id “app” and render our h1 tag. Now we have a full-stack app that is ready to be developed. (❁´◡`❁)
If you skipped all of the above and just want a ready-to-use solution, here it is. An archive with preconfigured folder structure and precalculated dependencies. All you need to do is set up a virtual environment (install all required Python packages) for the downloaded folder and install the required NPM packages in the Frontend app.
In the next article, I will show you the basic layout for a website and what it is going to look like.
Common errors, bugs and mistakes
Incorrect Project Structure
Mistake: Not organizing the project directory properly, leading to confusion and difficulties in managing both React and Django codebases.
Solution: Maintain a clear and logical directory structure. Keep frontend and backend code in separate directories.
Ignoring CORS Issues
Mistake: Overlooking Cross-Origin Resource Sharing (CORS) settings, which can lead to blocked requests.
Solution: Configure your Django backend to handle CORS. Use django-cors-headers to allow specific origins.
Inconsistent Environment Configuration
Mistake: Having conflicting or inconsistent environment configurations, leading to issues in development and production builds.
Solution: Ensure that environment variables are consistently defined. Use tools like dotenv for managing environment variables in both React and Django.
Incorrectly Handling Static Files
Mistake: Misconfiguring static file handling, which can lead to issues in serving React assets in Django.
Solution: Properly configure Django to serve static files and ensure React assets are placed in a directory Django can serve.
Ignoring Client-Side Routing Conflicts
Mistake: Ignoring potential conflicts between Django's and React Router's routing mechanisms, leading to broken links or incorrect routing.
Solution: Delegate client-side routing to React Router and ensure Django serves the React app for all relevant routes.
Comments
(0)
Send
Response for
>
It's empty now. Be the first (o゚v゚)ノ
Other
Similar articles
Used termins
- Django template ⟶ This is a text document marked up with a special syntax for inserting new code.
- Authentication ⟶ Is a process implemented on a website that checks if requested data can be sent to the source of the request. (By source, I mean user.)
- React ⟶ An open-source JavaScript library developed by Facebook for building user interfaces, particularly for single-page applications where you need a fast and interactive user experience. It allows developers to create reusable UI components, manage the state of their applications, and efficiently update the user interface in response to data changes.
- Django framework ⟶ Is a high-level, open-source web framework for building web applications using the Python programming language. It follows the model-view-template (MVT) architectural pattern and is designed to facilitate rapid development while promoting clean, pragmatic design.
Related questions
- When should I use inline-style vs. CSS? Use inline-styles for dynamic style properties. The CSS alternative provides more advantages, such as auto-prefixing, better debugging, media queries, keyframes.
- My App doesn't render correctly on the server? If it doesn't work, in 99% of cases it's a configuration issue. A missing property, a wrong call order, or a missing component – server-side rendering is strict about configuration. The best way to find out what's wrong is to compare your project to an already working setup. Check out the reference implementations, bit by bit.
- I can’t stand Django template language. Do I have to use it? I think this template engine is the best thing ever, but I know that choosing a template language runs close to religion. There’s nothing about Django that requires using the template language, so if you’re attached to Jinja2, Mako, or whatever it's ok.