Django is my favourite framework for web development. It speeds up a lot the process of coding your app. But one its biggest problems is that is more difficult to ingrate with a frontend framework, compared to Laravel. But here we will show you how to integrate them.
1. Compile Your react project
Go into your react project folder, that i assume is called frontend, and run the command:
npm run build
Now, a compiled version of your app is built inside the build folder. Remember the path of your app, it will be used later.
2. Edit settings file
Once you have compiled your React app, open your settings.py file in your Django project. Now, go in the TEMPLATES variable, and modify the key 'DIRS', adding the path to the built react app.
The code should look like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_DIR, 'frontend/build'),
],
'APP_DIRS': True,
....
}
Now, you should add your STATICFILES_DIRS variable, that is contained frontend/build/static
STATICFILES_DIRS =[
os.path.join(BASE_DIR, 'frontend/build/static')
]
3. Modify urls file
First of all you should import TemplateView in your file. then render as home page the index.html file of the built react app.
from django.views.generic import TemplateView
urlpatterns = [
path('',TemplateView.as_view(template_name='index.html')),
,]
Conclusions
That's all. It might seem more complex at first, but you can easily integrate your React frontend with your Django project.