[Django]-Django react render

2👍

We currently have integrated React mini apps into our existing Django project.

We simply return the context which includes the props:

class HelloWorld(DetailView):
    template_name = '/path/to/your/template.html'

    def get_context_data(self, **kwargs):
        props = {
            // your props/data
        }

        context = {
                'component': 'overview.js',
                'title': 'Hello World',
                'props': json.dumps(props)
            }

        return context

Then in a template we render our props into the global window scope:

<script>
    // Make sure to escape your props to prevent XSS! See here for the source
    // for the json filter: https://gist.github.com/pirate/c18bfe4fd96008ffa0aef25001a2e88f
    window.props = {{props|safe}};
</script>

<script src="/path/to/your/js/{{component}"></script>

Then in the React app, I render with the app name and pass in the window.props.

ReactDOM.render(React.createElement(OverviewApp, window.props), document.getElementById('root');)

You can read more about this approach here:

https://hackernoon.com/reconciling-djangos-mvc-templates-with-react-components-3aa986cf510a

Leave a comment