reactjs - React - parent component with child in separate dom containers -
is possible have component child components mounted different dom objects?
some pseudo-code explain wanna archieve:
import childcomponent1 './components/childcomponent1'; import childcomponent2 './components/childcomponent2'; var myparentcomponent = react.createclass({ render: function() { <childcomponent1 />, document.queryselector('#component-1') <childcomponent2 />, document.queryselector('#component-2') } }); reactdom.render( <myparentcomponent />, //inherit dom mounts );
this might not right way handle though - i'm open suggestions. want this, make myparentcomponent take care of state values etc. if add multiple reactdom.render() won't have parent component.
you can achieve using componentdidmount
, componentdidupdate
hooks manually render child components when parent component updates:
class child1 extends react.component { render() { const {count, onclick} = this.props; return ( <div onclick={onclick}>child 1 {count}</div> ); } } class child2 extends react.component { render() { const {count, onclick} = this.props; return ( <div onclick={onclick}>child 2 {count}</div> ); } } class app extends react.component { constructor(props) { super(props); this.container1el = document.queryselector("#container-1"); this.container2el = document.queryselector("#container-2"); this.handleclick = this.handleclick.bind(this); this.state = {count: 0}; } handleclick() { this.setstate({count: this.state.count + 1}); } renderchildren() { const {count} = this.state; const {handleclick, container1el, container2el} = this; reactdom.render(<child1 count={count} onclick={handleclick}/>, container1el); reactdom.render(<child2 count={count} onclick={handleclick}/>, container2el); } componentdidmount() { this.renderchildren(); } componentdidupdate() { this.renderchildren(); } componentwillunmount() { reactdom.unmountcomponentatnode(this.container1el); reactdom.unmountcomponentatnode(this.container2el); } render() { return null; } } reactdom.render(<app/>, document.createelement("div"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container-1"></div> <div id="container-2"></div>
Comments
Post a Comment