What I do is after serving the static content (built react app), there are entry points in the DRF API, which has a template, sets the server context (if you want to set any) in the clientConfig
object.
Also, you will need to create a separate "initializer" script for each endpoint with react routes in it, providing it the right selector which you will mention in the Django Templates.
URL: path('foobars', views.FooBarsView.as_view(), name='foobars')
View:
class FooBarsView(TemplateView):
template_name = 'foobars.html'
def get_context_data(self):
return {
"client_config": {}
}
Template (foobars.html):
{% load static from staticfiles %}
<head>
<link rel="stylesheet" href="{% static 'dist/css/foobars.css' %}"/>
</head>
<main class="foobars"></main>
<script type="text/javascript">
var clientConfig = {{ client_config|safe }};
</script>
<script type="text/javascript" src="{% static "dist/js/foobars.min.js" %}"></script>
Some changes in the React app you have to make, is to use the selector .foobars
in the render
method.
Initializer:
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Switch>
<Route name="index" exact path="/" component={FooBarComponent} />
</Switch>
</Router>
</Provider>,
document.querySelector(".foobars")
);