javascript - React - parent components render child components to different elements/nodes -
say have built site in plain old html+sass , want add little react in handle main content of site. have list of internal links in left col displays different content in right column (pretty tabs).
looking @ various articles seems though should have parent component manages state (perhaps state.currenttab) control main content should rendered.
my problem need parent component render left link , right content different elements. can't seem figure out how this.
i can see below nothing render both of reactdom.render()'s in myparent never gets called. problem seem need call/render 2 left , right cols in there able pass state updates each 1 can control content. , don't think can if sit @ bottom of app.js file outside parent component.
i'm sure i've made mistakes in below code explains enough want do.
could please help? :d
p.s may make little codepen if helps.
so the project might so:
index.html
body .container #leftcol <!-- render links element --> #rightcol <!-- render content element -->
app.js
class myparent extends react.component { constructor(props) { super(props); this.state = { currenttab: 0 } } reactdom.render(<conference currenttab="this.state.currenttab" />,document.getelementbyid('rightcol')); reactdom.render(<tabmenu />,document.getelementbyid('leftcol')); } class rightcol extends react.component { render(){ return( <div>right col mark etc</div> ) } } class leftcol extends react.component { render(){ return( <ul> <li><a href="tab1">tab 1</a></li> <li><a href="tab2">tab 2</a></li> <li><a href="tab3">tab 3</a></li> </ul> ) } }
since you're doing hard page loads (normal <a>
s), can access url in constructor in myparent , render based on that.
class myparent extends react.component { constructor(props) { super(props); this.state = { page: location.pathname.split('/').pop(), } } componentdidmount() { reactdom.render(<conference currenttab="this.state.currenttab" />,document.getelementbyid('rightcol')); reactdom.render(<tabmenu />,document.getelementbyid('leftcol')); } render() { if (this.state.page === 'tab1') { ... } } }
if want change client side routing, you'll make links preventdefault , use pushstate. can use eventemitter (new (require('events').eventemitter())
) , listen events in myparent in componentdidmount. in children can dispatch events after doing pushstate. you'll still capture initial url in myparent shown above.
Comments
Post a Comment