How to connect Django to React

In this tutorial We will learn how to connect Django with React Js using some basic steps.

I think that we are in a folder named django-react-app

  1. First, create a react app. Open your terminal and type

npx create-react-app my-react

2. Now, Create a Django projectdjango-admin startproject myDjango

3. Now drag and drop the react project to the Django project

4. After This go to the react project folder open a terminal and runnpm run build

And now you see react create a build folder, and in this folder, we work with two files index.html and style.css

5. Now we set the templates to build folder’s index.html. For that let’s go to the settings and in the templates section set the templates like this

‘DIRS’: [os.path.join(BASE_DIR, ‘my-react/build’),],

This will set the templates to the build folder

6. Now we have to set URLs. Open urls.py and import TemplateView and set this like below from django.urls import path


from django.views.generic import TemplateViewurlpatterns = [
path(‘admin/’, admin.site.urls),
path(”, TemplateView.as_view(template_name=’index.html’)),
]

now when anyone visite ‘ / ’ then react build folder’s index.html will be display

7. Now the last step is to Set the Static files to the build folder’s style.cssSTATICFILES_DIRS = [os.path.join(BASE_DIR,‘my-react/build/static’),]

Now your templates, URLs, Static is set and you are Good to go. Run the server and open 127.0.0.1:8000 to your browser and you will see the react home pagepython manage.py runserver

Important Note

Leave a Reply

Your email address will not be published. Required fields are marked *