Jose Carrillo Jose Carrillo - 1 month ago 11
React JSX Question

Using React in a multi-page app

I have been playing around with React and so far I really like it. I am building an app with NodeJS and would like to use React for some of the interactive components across the application. I do not want to make it single page app.

I haven't yet found anything on the web that answer the following questions:

How do I break up or bundle my React components across a multi-page app?

Currently all my components are in one file even though I may never load them in some sections of the app.

So far I am trying using conditional statements to render components by searching for the ID of the container where React will render. I am not 100% sure of what the best practices are with React. It looks something like this.

if(document.getElementById('a-compenent-in-page-1')) {
React.render(
<AnimalBox url="/api/birds" />,
document.getElementById('a-compenent-in-page-1')
);
}

if(document.getElementById('a-compenent-in-page-2')) {
React.render(
<AnimalBox url="/api/cats" />,
document.getElementById('a-compenent-in-page-2')
);
}

if(document.getElementById('a-compenent-in-page-3')) {
React.render(
<AnimalSearchBox url="/api/search/:term" />,
document.getElementById('a-compenent-in-page-3')
);
}


I am still reading the documentation and haven't found what I need yet for a multi page app.

Thanks in advance.

Answer

Currently, I am doing something similar.

The application is not a full React App, I am using React for dynamic Stuff, like CommentBox, which is autark. And can be included at any Point with special params..

However, all my sub Apps are loaded and included into a single file all.js

When I need to include an App into the SSR Templates, I just have to include a DIV with the class "__react-root" and a special ID, ( the name of the React App to be rendered )

The logic is really simple:

import CommentBox from './apps/CommentBox;
import OtherApp from './apps/OtherApp';

document
  .querySelectorAll('.__react-root')
  .forEach(renderAppInElement)

const AppsMap = {
  CommentBox: CommentBox,
  OtherApp: OtherApp
};

function renderAppInElement(el) {
  var App = AppsMap[el.id];
  if (!App) return;

  ReactDOM.render(<App />, el);
}

What do you think?

Comments