Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically insert react components into another react component

Right now I have a sidebar that I want to use for various forms and bits of information. I'm using the global event system to trigger the opening of the sidebar, but I'm not sure how to inject react components into the sidebar react component.

I started by trying this

componentWillMount: ->
  window.toggleSidebar = (react_component)=>
    React.renderComponent(react_component(), document.getElementById('sidebar-content'))
    @toggleSidebar()

But this didn't work once all of the components are mounted because you can't call render component into an element that is inside another component.

So is there an accepted way to pass any react component into another component?

like image 821
Blaine Hatab Avatar asked Dec 08 '25 19:12

Blaine Hatab


1 Answers

You don't actually want to pass a component instance, you want to pass the component factory and data that it can use to render the component.

events.emit('sidebar-change-request', {component: Foo, props: obj, open: true});

And in the sidebar component it'd be listening to the event:

  getInitialState: -> component: React.DOM.div, props: {}, open: false

  # standard event emitter stuff    
  componentDidMount: -> 
    events.addListener 'sidebar-change-request', this.handleSidebarChangeRequest

  componentWillUnmount: ->
    events.removeListener 'sidebar-change-request', this.handleSidebarChangeRequest

  # simply apply the payload to state
  handleSidebarChangeRequest: (payload) ->
    this.setState payload

  # dynamically render stuff
  render: ->
    if this.state.open
       React.DOM.div {className: "sidebar"},
          this.state.component this.state.props
    else
       React.DOM.div null

If you needed to get some information back from the component renered in the sidebar, you'd pass a callback to that components via props; or the component could emit events.

like image 89
Brigand Avatar answered Dec 10 '25 09:12

Brigand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!