django-react-components and it's sibling package django-react-loader facilitate using individual react components
in a django template with a simple template tag. This also webpack, and the paired packages webpack-bundle-tracker
and django-webpack-loader to compile the react components and make them available within django.
For normal usage, first install django-react-components using pip:
$ pip install django-react-componentsAdd 'django_react_components' and 'webpack_loader' modules to your INSTALLED_APPS in settings.py:
INSTALLED_APPS= (
...,
'django_react_components',
'webpack_loader',
)Install Webpack 5 Installation Guide The command may resemble:
npm install --save-dev webpackInstall django-react-loader with your preferred package manager:
$ npm install --save-dev django-react-loader or
$ yarn add django-react-loader --devConfigure Webpack: Webpack Configuration Guide. The rest of this guide assumes a webpack config file (probably called webpack.config.js)
Follow instructions in the Django Webpack Loader Docs
Modify the webpack config file so that django-react-loader loads the react files:
* Import the django-react-loader
* Specify ENTRIES - a mapping of the names of your components to the source code file
* Add django-react-loader to loaders
Example configuration outline:
//wepback.config.jsconstDjangoReactLoader=require('django-react-loader');
...,constENTRIES={
...,nameOfComponent: componentImportPath}...,module.exports={
...,module: {rules: [
...,{test: /\.js$/,exclude: /node_modules/,options: {entries: ENTRIES},loader: DjangoReactLoader}...,Compile your react components with webpack.
Command likely to resemble webpack build
In your templates, you can render React components by using the {% react_component %} or the {% react %}template tag. To do so:
- Load the template tag and the
render_bundletag fromdjango_webpack_loader:
{%loaddjango_react_components%}
{%loadrender_bundlefromwebpack_loader%}- Use
render_bundleto pull in the appropriate javascript
<head>
{% render_bundle 'runtime' %}
{% render_bundle 'App' %} </head>
3a. Use the react_component tag to render the component with keyword arguments as props
<body>
{% react_component 'App' component_id='app' prop1=prop1 prop2=prop2 %}
</body>
3b. Use the react/endreact tags to render the component with rendered content inside. This will be passed as raw HTML to the component as the children prop.
<body>
{% react 'App' id='app' %}
<h1>Hello World</h1>
<p>{{ content }}</p>
<a href='{% url 'endpoint' %}'>Link</a>
{% endreact 'App' id='app' %}
</body>
django_react_components uses JSON to encode props into the React components. You can specify a custom JSON encoder
class with the DJANGO_REACT_JSON_ENCODER settings in your settings file, otherwise the default DjangoJSONEncoder is used.
The encoder will be passed to json_script()
Python 3.11, Django 4.2