Search code examples
javascriptreactjscreate-react-app

How can I use the same React app in multiple locations of the same page?


I have created a small calculator app using create-react-app.

At the moment it's a local standalone app I'm developing. My aim is to integrate this into an existing server-side rendered website.

I am wondering on a few things:

  1. How would I integrate this app from create-react-app into an existing website?
  2. How would I be able to embed the React app in multiple locations of the same page?

When it comes to initialising the app at the top level, I am currently doing:

render(<App />, document.querySelector('#app'));

But that only allows me to place it into one area.

What is the best way to have multiple apps? It doesn't matter if they do not maintain the same state with one another and operate independently.

Thank you.


Solution

  • You can simply render the app in multiple containers.

    var Hello = React.createClass({
      render: function() {
        return <div>Hello {this.props.name}</div>;
      }
    });
    
    ReactDOM.render(
      <Hello name="World" />,
      document.getElementById('container1')
    );
    
    ReactDOM.render(
      <Hello name="World" />,
      document.getElementById('container2')
    );
    

    Here an example