Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.render replace container instead of inserting into

Tags:

reactjs

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?

like image 420
Ronnie Avatar asked Jun 06 '15 19:06

Ronnie


People also ask

Does ReactDOM render replace?

Both render and hydrate have been replaced with new client methods in React 18. These methods will warn that your app will behave as if it's running React 17 (learn more here).

What does ReactDOM render do?

The ReactDOM. render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

What is ReactDOM in React?

What is ReactDOM? ReactDOM is a package that provides DOM specific methods that can be used at the top level of a web app to enable an efficient way of managing DOM elements of the web page.

How do I stop Rerendering components in React?

If you're using a React class component you can use the shouldComponentUpdate method or a React. PureComponent class extension to prevent a component from re-rendering.


1 Answers

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")); 
like image 123
WiredPrairie Avatar answered Oct 03 '22 16:10

WiredPrairie