DEV Community

Cover image for How to connect React js with Django
Shivam Rohilla
Shivam Rohilla

Posted on

How to connect React js with Django

Hello Everyone, in this post you'll learn how to connect react js with Django in simple steps.
As you guys know React js is a very powerful and famous frontend js library and some people suggest react as a framework.

Today we connect react js with one of the most powerful backend framework Django.

Step1:- Create a django project

django-admin startproject backend
Enter fullscreen mode Exit fullscreen mode

Step2:- Now Create a virtual environment

virtualenv envrec
Enter fullscreen mode Exit fullscreen mode

Step3:- Install Django Rest Framework in a virtual environment.

pip install django djangorestframework
Enter fullscreen mode Exit fullscreen mode

Step4:- Now make a frontend app.

django-admin startapp frontend 
Enter fullscreen mode Exit fullscreen mode

Step5:- Now add this app and rest framework in Installed Apps:-

INSTALLED_APPS = [

    'rest_framework',
    'frontend',
]
Enter fullscreen mode Exit fullscreen mode

Step6:- Now write some URLs in your project urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('frontend.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Step7:- Now create some urls in your app

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index)
]
Enter fullscreen mode Exit fullscreen mode

Step8:- Now write a basic command in your app views.py file

from django.shortcuts import render
def index(request):
    return render(request, 'build/index.html')
python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Now finally run this command and your Django project start running on your localhost server

Now we set up react project.

for Setting up a react project install Node js and some other requirements in your pc.

Open a terminal and run this command.

npx create-react-app frontend
Enter fullscreen mode Exit fullscreen mode

After running this command your project will be created successfully.

Now run the react project

npm run build
Enter fullscreen mode Exit fullscreen mode

Final Steps for connection.
Write the react app path in settings.py DIR

'DIRS': [os.path.join(BASE_DIR, '../frontend')],
Enter fullscreen mode Exit fullscreen mode

and for serving static files paste this command at the bottom in settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, '../frontend/build/static'),
]
Enter fullscreen mode Exit fullscreen mode

that's it. your settings and connection is done now run the project.

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Top comments (0)