Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I append my component to a div's existing content in ReactJS?

Tags:

reactjs

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"));
like image 682
Diablo3093 Avatar asked Jun 03 '16 02:06

Diablo3093


2 Answers

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!

like image 124
P.M. Avatar answered Nov 05 '22 14:11

P.M.


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

like image 26
Shubham Khatri Avatar answered Nov 05 '22 16:11

Shubham Khatri