How to integrate React with Django

Posted by

Open two terminals(cmd) on Your Desktop.
(You can also create it in any drive path.)

In First Terminal Create Django Project(here we are giving the name as Reango) with this Command.

C:\Users\admin\Desktop>django-admin startproject Reango

In second Terminal create react project(here we are giving the name as reactapp)with this Command.

C:\Users\admin\Desktop>create-react-app reactapp

Then Move reactapp folder into the Reango folder.

Then We need to specify template path and static path of react to the django.
(index.html in the build folder of react is our main file template and and we also need to specify the static folder path in build folder )

Add os.path.join(BASE_DIR,‘reactapp/build’) your in template directory of setttings.py

‘DIRS’: [

os.path.join(BASE_DIR,‘reactapp/build’),
]

add STATICFILES_DIRS at the end of settings.py

STATICFILES_DIRS=[
os.path.join(BASE_DIR,‘reactapp/build/static’), ]

add TempalteView generic view in your urls.py so it will render the template with that specific template name.

your urls.py will look like this.

from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘ ’,TemplateView.as_view(template_name=‘index.html’)), ]

here u can start servers but we will create some different view.

go to App.js file remove unnecessary things and Add this code.

import React from ‘react’;

import ‘./App.css’;

function App() {
return (
<div className=”App”>
congraTulation YoU havE creAted React+djanGo ConFiguration..
</div>
);
}

export default App;

Add this In your App.css

.App{
background-color: black;
color: antiquewhite;
}


In your other cmd start react server

C:\Users\admin\Desktop\Reango\reactapp>npm build

In your one cmd start django server

C:\Users\admin\Desktop\Reango>python manage.py runserver

Go to Browser and type localhost:8000(default django server)

You will get this:-

(dont’t worry about image i have set my background-image as this solar image)

WOOOOOOOOOOOOOOOOOOOO!!!!!!!!!! You Are Done with the (REACT+DJANGO) integration.

**CONGRATULATIONS!!!!**

That’s it!! Thank You.

I  have written the same article on  Medium  as well. 

If you also wish to share your knowledge with the TheCodeSpace fam kindly share your thoughts/article on rajparmar2308@gmail.com.

2 comments

Leave a Reply

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