Skip to content
Advertisement

Django project not rendering React.js

In my project, I am trying to tie together Django and React.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" /> {% load static %}
    <link rel="icon" href="{% static 'logofavicon.ico' %}" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta property="og:image" content="{% static 'Banner.png' %}">
    <meta name="description" content="The future of digital content" />
    <link rel="apple-touch-icon" href="{% static 'logo192.png' %}" />
    <link rel="manifest" href="{% static 'manifest.json' %}" />
    <title>Drop Party</title>
</head>

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <script type="module" src="{% static 'index.js' %}"></script>
    <div id="root"></div>
</body>

</html>

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "./styleguide.css";
import "./globals.css";

ReactDOM.render( <
    React.StrictMode >
    <
    App / >
    <
    /React.StrictMode>,
    document.getElementById("root")
);

reportWebVitals();

settings.py

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/frontend/'

STATICFILES_DIRS = (
    FRONTEND_DIR / 'build', FRONTEND_DIR / 'src', FRONTEND_DIR / 'public'
)

Project Hierarchy

Project Hierarchy

I have looked at this post, and confirmed that this solution is not applicable for me.

The primary issue, I think, is that Django is serving the html, but not running the .js, so I’m unsure of where to go with this.

I have also confirmed that the image linking is working as well, so I’m not getting 404 errors or anything like that.

Secondary, semi-related question: Should I be linking the favicons like this? I get the feeling I shouldn’t be serving the html statically, but I was unable to find how exactly to serve the project, other than serving the html statically.

(edit) I have added in the script as in comments, but now I get an error where Django seems to reject the React tags.

Advertisement

Answer

Your HTML file has no <script> tag for your index.js (although, interestingly, it does have a <noscript>).

You need to tell your page about every JS file you want to run, which you do by using <script> tags.

See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script for more info.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement