Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put ReactDOM.render in React

Tags:

reactjs

Here is the Getting Started example of react, in the example, the bellow code fragment is in separate main.js file:

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('example')
);

What if there are pages that don't contain id: 'example', e.g. home.html(only have id:example1), index.html(only have id:example2), then how to reuse <h1>Hello, world!</h1> in those pages ?

like image 746
fudy Avatar asked Jan 28 '16 07:01

fudy


1 Answers

You have a valid problem. You can abstract the hard coded #id part from the main.js file. Instead of thinking main.js as a self bootstrapping React app, just expose a parametric version of it.

Here is new main.js

window.renderApp = function(id){
  ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById(id)
  );
};

And in your presumably index.html file

<div id="newID"></div>
<script src="main.js"></script>
<script>
  renderApp('newID');
</script>

I have seen this approach used, and I myself used this in several production React apps. Basically it is not logical to bind your React app with a hard coded id parameter.

like image 114
Kemal Dağ Avatar answered Oct 26 '22 23:10

Kemal Dağ