Wednesday, 5 July 2023

handle many html files with React and Django

I have a hybrid django+react implementation. Django renders the initial HTML, then react takes control. However, the URLs are managed by Django.

In react, the index.js file is supposed to correspond with one html right? Please correct me if I'm wrong. So, which is the correct approach if I have several HTML files that need react. My index.js file looks like this:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import { EfestoComponent, WorkTimeComponent, AresComponent } from './components/pulseHome';
import { PulseComponent} from "./components/pulseHistory";

import reportWebVitals from './reportWebVitals';

const efestosData = JSON.parse(document.getElementById('efestos-data').textContent);

const efesto = ReactDOM.createRoot(document.getElementById('efesto'));
const worktime = ReactDOM.createRoot(document.getElementById('worktime'));
const ares = ReactDOM.createRoot(document.getElementById('ares'));

const pulse = ReactDOM.createRoot(document.getElementById('pulse'));


efesto.render(
  <EfestoComponent objects={efestosData}/>
);

worktime.render(
    <WorkTimeComponent/>
)

ares.render(
    <AresComponent/>
)

pulse.render(
    <PulseComponent/>
)

As you can see, the efesto, worktime and ares components belong to 1 js file called pulseHome, it holds the components for a file called pulse_home.html. Then the pulse component lives in a pulseHistory js file which holds the components for a pulse_history.html. When I visit any of the two htmls, it raises the error:

Uncaught TypeError: document.getElementById(...) is null

of course, since the first elements are not present in the second html, and vice versa. I could solve it with some hacky code (the AI suggests creating another index2.js file), but there must be for a correct and standard approach. I'm kind of new to React. Any advice will help.



from handle many html files with React and Django

No comments:

Post a Comment