Ian
Ian

Reputation: 174

How to include the same React app twice on the same page?

I have a simple app created using CRA v2 that provides a "load more" button after lists of posts. The default posts displayed on the page are generated server-side based on a set of criteria (ie. specific post type, taxonomy terms, etc), and the "load more" button queries an API to display more posts that match the same criteria.

My pages will have an undefined (but >1) number of post lists on a page, and not all of the lists will be nearby each other, so the whole thing can't exist in a single app. I need to be able to render the app more than once per-page and have them operate independently.

Best case scenario, I'd be able to do something like this:

<ul class="posts  posts--foo">[first list of posts from the "foo" post type go here]</ul>

<div id="app-root" data-post-type="foo"></div>


<ul class="posts  posts--bar">[second list of posts from the "bar" post type go here]</ul>

<div id="app-root" data-post-type="bar"></div>


<script src="main.7a3cc682.js"></script> <!-- built script-->

I realize this won't work as written. Is this possible, and if so what's the best way to make this work?

Upvotes: 0

Views: 873

Answers (1)

Ian
Ian

Reputation: 174

I was able to find a solution using the answer to this question. Here's what it looks like:

index.js

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

window.mount = function(id) {
  let app = document.getElementById(id);
  ReactDOM.render( <WPLoadMore {...(app.dataset)} />, document.getElementById(id) );
}

and then in my HTML:

<script src="build/static/js/main.7a3cc682.js"></script>

<ul class="posts  posts--foo"></ul>
<div id="app1" data-post-type="foo"></div>
<script type="text/javascript">mount("app1");</script>

<ul class="posts  posts--bar"></ul>
<div id="app2" data-post-type="bar"></div>
<script type="text/javascript">mount("app2");</script>

The only slightly wonky bit about this is that in the index.html in my public directory, I needed to move the mount() outside of the </body> tag so that it loads after all of the React scripts, like so:

  </body>
  <script type="text/javascript">mount("wplm");</script> <!-- included outside the body so this works in development -->
</html>

Upvotes: 1

Related Questions