Is it possible to add a component to a div with existing content in ReactJS?

When we use ReactDOM.render(<Component/>,document.getElementById("container"));, the component gets a visualization of the mentioned element. What if the div here already has some existing content inside it? Can React add a rendering component to it? eg:

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"));
+4
source share
3 answers

As far as I can tell, this is the only way to do what you ask for (since I tried to do the same):

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 / improved way to add a component reactto an existing one <div>without first installing a new empty one <div>, please call!

+1
source

div .

    <script src="https://facebook.imtqy.com/react/js/jsfiddle-integration.js"></script>
<div class = 'outer-container'>
<p>
I can see this hello.
</p>
<div id="container">
    <!-- This element 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'));

: JSFIDDLE

0

You should have a container container for things you don’t want to redefine. It should be something like:

<div id='wrapper-container'>
   <p>Hello, React! Content before</p>
   <div id='container'></div>
   <p>Content after</p>
</div>
0
source

All Articles