React + Django Integration in a few simple steps
Integrating React with Django is something I always wanted to do. I saw some tutorials which over-complicated things so I thought I’d make a simplified walk-through tutorial.
I will assume you already have an understanding of how both Django and React work. It’s important to know how Django serves templates and static files as well as what happens when you run npm run build
in React.
The key difference is we’ll be telling Django to look for templates and static files inside our React app. Later you can use the Django REST framework to serve your model data.
Let’s get started!
We’ll start by opening a terminal and running django-admin startproject django_react_template
and cd
into our default Django application.
Now we'll run npx create-react-app react_frontend
to create our React app inside our Django project.
We now have a fresh React app in the root of our Django directory.
After we create the React app we can cd
into the React directory and run npm run build
to compile our app.
You’ll notice we now have a build
directory. This is where we’ll tell Django to look for templates and static files.
static
directory and an index.html
file.Next we’ll go into our settings.py
file in our Django project and show Django where we want it to look for templates.
First, import the os
module in settings.py
. We’ll need it for the next step.
Add the code above to your settings.py
. This tells Django to look for templates in the build
directory of our React app. There, it will find the index.html
of our compiled app.
TemplateView
will allow us to use our template without having to call a view.
We’re almost done! Let’s configure static files in our settings.py.
Similar to the previous step, we’ll tell Django to look for static files (css, js etc.) in the build
directory of our React app.
Hooray! We’ve just integrated Django with React!! When you are writing your React code just run npm run build
and Django will serve our static files along with our updated index.html
we pointed to in urls.py
.
We can now build out an API with the Django REST Framework and utilize React’s amazing… reactive-ness?
Part 2??