[Django]-Using React with Django, do I need react-router?

2👍

@Marc, I think you are on the right track with what’s been given to you.
I agree with @SrThompson’s answer, but I’d make some slight changes:


Starting with Django. In your testview.html:

{% extends "base.html" %}
{% load render_bundle from webpack_loader %}

{% block main %}
<div id="{{component_name}}"></div>
{% render_bundle 'vendors' %}
{% render_bundle component_name %}
{% endblock %}

So, there would be a component_name context variable that defines the component being rendered by react and also sets the ID of the main div.


Jumping to React, you could have a render.js file that would be like this:

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../somewhere';    

const render = Component => {
  ReactDOM.render(
    <App>
      <Component />
    </App>,
    document.getElementById(Component.name)
  )
}

export default render;

This render function takes the Component you passed as a parameter and renders it to the element with id='Component', just like you set in the context variable in Django. You also get the App component on top of every rendered component, just as a normal react app would work. Just call them using render(App1.jsx) for instance.


This way you would have to worry about creating only a single .hmtl file for rendering the react components.

1👍

react-router is a Frontend router meant to be used on Single Page Applications. If you’re not building a SPA you don’t need it.

You can hook up a react parent component anywhere you want, it’s pretty flexible that way, but yes, if you want to go the server-side rendering way with your Django views and use react to enhance parts of it, then yes, you would need App2.jsx, App3.jsx, etc. (I would suggest picking better names though)

Also, if you’re going this way, don’t use react to build the full page, only use it where you need the extra interactivity, like a widget or something. If you’re rendering the entire page in react without making the app a SPA you lose the benefits from both the JS client app and server-side rendering

You can’t pass variables from django views to react components, because they’re rendered on the browser. Whatever data you need in your react components has to be fetched with an AJAX request, just like any other JS library

Leave a comment