0

I have a Django view through which I want to render a React component. But unable to do so. This is my Django template.

{% extends "base.html" %}

{% block javascript %}

    <script>
        window.props = {{props}};  // 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.react_mount = document.getElementById('react');
    </script>
    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js" crossorigin></script>
    <script src="/static/components/{{component}}" type="text/babel"></script>

{% endblock javascript %}

{% block content %}

<div class="container">
    <div class="card">
        <div class="card-body">
          <div id="react">
              <!-- Contents get replaced by mounted React.Component -->
              <i class="fa fa-lg fa-spinner fa-spin"></i><br><br>
              <i class="pending">Loading components...</i><br><br>
          </div>
        </div>
    </div>
</div>

{% endblock content%}

This is my React component.

import React from 'react'
import ReactDOM from 'react-dom'

class HelloWorld extends React.Component {

    render() {
        return <h1>Hello World!</h1>;
    }

}

ReactDOM.render(
    React.createElement(HelloWorld, window.props),    // gets the props that are passed in the template
    window.react_mount,                                // a reference to the #react div that we render to
)

I am getting following error:

Uncaught ReferenceError: require is not defined

enter image description here

ARKhan
  • 1,724
  • 22
  • 30
  • That is js error, however this part `src="/static/components/{{component}}` references static files in non django way, see this answer for details https://stackoverflow.com/questions/66437690/django-html-template-cant-find-static-css-and-js-files/66439076#66439076 – Ivan Starostin Apr 04 '21 at 07:45

1 Answers1

0

I followed this solution and it works. The problem was that I need to configure webpack (see webpack.config.js file) which bundles the JS files.

ARKhan
  • 1,724
  • 22
  • 30