DEV Community

Discussion on: How to connect Django to ReactJs

Collapse
opauloantonio profile image
Paulo Antonio

Great article but I'd like to add two things:

If you're using Git, React includes /build in its gitignore so that builds won't go into the repository but since you're serving your React app from Django, the build also needs to be in the project as if it were the standard templates and static files.

That's why I usually rename my build folder to something like react_build and use this name in my Django settings file.

Another thing, in a React SPA, React itself should take care of the routes and display the proper components, probably with react-router. In your example, what happens if I create a page in my React app in /dashboard for instance and go to 127.0.0.1:8000/dashboard ?

Django will throw a 404 because there's no /dashboard in the urls.py but that should not have been handled by Django but by React.

For that problem, what I'm doing is using a regex in urls.py that captures any path that should not be handled by Django and redirect them to the React app.

So for instance, my base urls.py will contain /admin, /api, /static and some other specific files and after all those, the regex that sends the React app back to any URL path so that React itself does the routing and display the appropriate components or a 404 page. My current regex is:

re_path('(?!.*(static))', TemplateView.as_view(template_name="index.html", content_type="text/html"))

Need to import re_path from django.urls and import TemplateView from django.views.generic or replace it with a view like in your example.

I hope that makes sense.

Collapse
nagatodev profile image
Faruq Abdulsalam Author

Yes it does. Thanks for reading. I'll look into the points you raised.