django-create-react-app is a package that seamlessly integrates React with a Django project using the Create React App (CRA) template. It supports both development and production modes of a React application.
- Works with the
asset-manifestplugin on the frontend, maintained by Create React App. - No frontend code modifications are needed for Single Page Applications (SPA).
- In development mode, it works with the frontend server via HTTP (
localhost:3000).
Install the package via pip:
pip install django-create-react-appAdd "create_react_app" to your INSTALLED_APPS in Django:
INSTALLED_APPS = [
# Other apps...
'create_react_app',
]To create the build directory for the React app, run:
yarn build
# or
npm run buildThis will create a build directory inside your React app folder. Configure Django to reference this directory:
REACT_BUILD_DIRECTORY = os.path.join(BASE_DIR, 'app', 'react', 'build')Tell Django to treat the build folder as a static directory:
STATICFILES_DIRS = (
os.path.join(REACT_BUILD_DIRECTORY, 'static'),
)Add the following settings to manage the React app configuration:
CREATE_REACT_APP = {
'DEFAULT': {
'BUNDLE_DIR_NAME': REACT_BUILD_DIRECTORY,
'FRONT_END_SERVER': "http://localhost:3000/",
'IS_DEV': False,
}
}To load your React app in Django templates, use the following template tags:
{% load react_bundle_loader %}
<html>
<head>
{% render_bundle_css %}
</head>
<body>
...
{% render_bundle_js %}
</body>
</html>If your project has multiple React apps, configure them like this:
CREATE_REACT_APP = {
'DEFAULT': {
'BUNDLE_DIR_NAME': REACT_BUILD,
'FRONT_END_SERVER': "http://localhost:3000/",
'IS_DEV': False,
"PUBLIC_PATH_DEV": "http://localhost:3000/",
"PUBLIC_PATH": "/static/",
},
'ADMIN': {
'BUNDLE_DIR_NAME': REACT_BUILD,
'FRONT_END_SERVER': "http://localhost:3000/",
'IS_DEV': False,
},
}IS_DEV: True: Ensure the React app is running on theFRONT_END_SERVERat the specified port.IS_DEV: False: Ensure the build path points to the correct build directory.
{% load react_bundle_loader %}
<html>
<head>
{% render_bundle_css "ADMIN" %}
</head>
<body>
<div id="root"></div>
{% render_bundle_js "ADMIN" %}
</body>
</html>You can use the is_preload=True option to preload assets in your template:
{% render_bundle_css is_preload=True %}You can add extra attributes to the generated tags:
{% render_bundle_js attrib="async" %}
{% render_bundle_js attrib="disabled" %}When upgrading from version 0.8.4 to 0.9, the is_dev setting has been renamed to IS_DEV. Ensure you update your configuration as lowercase is_dev will no longer work.
- The
PUBLIC_PATH_DEVdefault value isFRONT_END_SERVER, useful for Docker setups. - Use
PUBLIC_PATH_DEVwith Docker forhttp://localhost:3000/. FRONT_END_SERVER:host.docker.internal.
When using Django's storage systems (e.g., AWS), change PUBLIC_PATH to your storage path:
PUBLIC_PATH = "https://234234234.aws.com/static/"