Django Templates And React Components

Nov 06, 2022 2 minutes read
Photo by olia danilevich (pexels.com)

When you think about Django web app the first thing you probably got in mind is Django + DRF (Django Restful Framework). But sometimes you need something different. In this short article I will try to explain how to use React components with Django templates. Using templates with npm setup in Django is not so popular, but if you got something like that let's see what you can do!

The library we are gonna use is react-supervisor.

# this package helps
npm i react-supervisor
# optional, if you haven't installed it yet
npm i react react-dom

To proceed you will need a javascript bundler like webpack or rollup. Everything depends on your needs. You need to find out what's the best strategy for your project. In other frameworks such as Laravel, Symfony or even RoR using npm things is much easier than in Django templates. I think that's why dividing your app into frontend and backend with DRF is most popular way to go in Django world.

Let's assume that you configured the npm setup. We are ready to use it, let's create a simple component and register it with react-supervisor.

// some entrypoint of your javascript files
import React from "react";
import { ReactSupervisor } from "react-supervisor";

const MyComponent = (props) => {
	return <button>Hello {props.name}</button>
};

ReactSupervisor.registerComponent(".my-selector", MyComponent)
ReactSupervisor.initialize();

Let's check what we got in Django views

# views.py

def example_view(request):
    return render(request, 'example.html', context={ "some_value": "Pass to react!" })

And check what's inside the template

<!-- example.html -->
{% extends "base.html" %}  

{% load static %}  

{% block content %}  
    <div class="my-component" data-name="{{ some_value }}"></div>
    <script src="{% static 'index.js' %}"></script>
{% endblock %}

Summary

Usually dividing your app into frontend and backend is much better, but sometimes it's not possible because of legacy code and so on. And for that cases doing it that way could make your django-templates development much more enjoyable. 

Disclaimer: The opinions expressed here are my own and do not necessarily represent those of current or past employers.
Comments (0)