Search code examples
reactjs

React.render replace container instead of inserting into


I'm gradually replacing some Backbone views with React.

My React View:

<div id="reactViewContent">Rendered By React</div>

I need to render the React view below other html elements without replacing them.

<div id="somestuff">
  <div id="anotherView">Other stuff not to delete</div>
  <div id="placeholderForReactView"></div>
</div>

I'd like that my method could replace the placeholder instead of inserting into it so that :

React.render(React.createElement(MyTestReactView), document.getElementById('placeholderForReactView'));

could result in:

<div id="somestuff">
  <div>Other stuff not to delete</div>
  <div id="reactViewContent">Rendered By React</div>
</div>

instead of:

<div id="somestuff">
  <div>Other stuff not to delete</div>
  <div id="placeholderForReactView">
    <div id="reactViewContent">Rendered By React</div>
  </div>
</div>

Without recurring at Jquery is there a correct way to do it?


Solution

  • You don't need jQuery to work around this issue.

    You just need to render into a temporary DIV and extract the content and replace the existing element. I've added the id="destination" so that the element can be easily retrieved from the temporary element.

    var Hello = React.createClass({
        render: function() {
            return <div id="destination">Hello {this.props.name}</div>;
        }
    });
    
    // temporary render target
    var temp = document.createElement("div");
    // render
    React.render(<Hello name="World" />, temp);
    // grab the container
    var container = document.getElementById("container");
    // and replace the child
    container.replaceChild(temp.querySelector("#destination"), document.getElementById("destination"));