When we use ReactDOM.render(<Component/>,document.getElementById("container"));
The component gets rendered to the element mentioned. What if the div here already has some existing content inside it? Can React append the rendered component to it? e.g:
HTML:
<div id = "container">Hello, React!</div>
JSX:
var Component = React.createClass({
render: function(){
return(
<p>Hello to you too!</p>
)
}
})
ReactDOM.render(<Component/>, document.getElementById("container"));
As far as I can tell, this is the only way to do what you're asking (as I was trying to do the same thing):
let divs = document.getElementsByClassName("some_class")
for (let i = 0; i < divs.length; i++) {
const id = Math.random() //or some such identifier
const d = document.createElement("div")
d.id = id
divs[i].appendChild(d)
ReactDOM.render(<SomeComponent/>, document.getElementById(id))
}
If anyone knows of a cleaner/better way to append the react
component to the existing <div>
without first attaching the new empty <div>
, please chime in!
When you render a react component in a div, its contents are being replaced by the contents of the component you created.
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div class = 'outer-container'>
<p>
I can see this hello.
</p>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
Hello React
</p>
</div>
</div>
JSX
var Hello = React.createClass({
render: function() {
return (
<div className="Button">
<span className="left" onClick={function() {alert("left")}}>Left</span>
<span className="right" onClick={function() {alert("right")}}>Right</span>
<span className="middle" onClick={function() {alert("middle")}}>Middle</span>
</div>
);
}
});
ReactDOM.render(<Hello name="World" />, document.getElementById('container'));
You can see a fiddle here: JSFIDDLE
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