Folder structure for React and Django REST

Viewed 5774

I'm in the process of refactoring a rather basic/traditional Django webapp to a more modern React-plus-Django-REST setup. I'm far more familiar with Django than React, so where to put the React part is what's confusing to me.

My question is: what are the best practices for folder structure in using both Django and React? Ideas I've had:

  1. Put all React files in their own folder like this: . ├── app1 │   └── example-files.py ├── app2 │   └── example-files.py ├── manage.py ├── react-django-project │   ├── settings.py │   └── urls.py ├── requirements.txt ├── some-app-1 │   └── example-files.py ├── some-app-2 │   └── example-files.py ├── src │   └── components │   ├── component1.js │   └── component2.js └── ...

  2. Put all React files in the static folder, but this doesn't seem right to me.

Is there an established set of best practices for this?

3 Answers

I agree with Igonato about having separate projects for frontend and backend. As client(Frontend) would make Ajax(API) calls to the server(Backend) and with the response data, client renders the page.

Especially with react, you need to convert the react code to minified js and css for higher performance on the production server.

You may use djangorestframework in the backend and setup a django server. For frontend, here are a couple of options: 1. you can use dva (if you intend to use redux). dva is good. I would recommend not to use redux until the state management in your application gets complicated. 2. If you are not gonna use redux, then you can use create-react-app

For front-end I would recommend to use antd if you want to go for material design based application. It's quite a lot of UI elements that you would need in your application. It's battle tested. I have used it in ~9 applications, I have made in the past 6 months.

As the others mentioned, using different repositories is the common approach to solve this. However for a smaller team / smaller project a single repository should suffice.

To keep everything in one repo you create a separate for folder for the react app, usually I name it projectname-client. If you are using create-react-app you could serve the index.html from the build folder by adding that path to settings file.

# settings.py
# Path to the frontend app build directory
BUILD_DIR = os.path.join(BASE_DIR, '{{ project_name }}-client/build')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BUILD_DIR
        ],
        ...
    },
]
STATICFILES_DIRS = [
    os.path.join(BUILD_DIR, 'static'),
]

# urls.py
urlpatterns = [
    ...
    path('', TemplateView.as_view(template_name='index.html'), name='index'),
]

If you are interested, I'm working on a django-admin startproject template that sets up the project to work with create-react-app. You can take a look here.

Related