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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With