Dynamically insert reacting components into another reacting component

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

I started with this

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

      

But it didn't work when all the components were installed, because you cannot call the render component on an element that is inside another component.

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

+3


source to share


1 answer


You don't actually want to pass an instance of a component, you want to pass a factory component 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 will listen for 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 need to return some information from a sidebar component, you must pass a callback to those components via props; or the component can fire events.

+5


source







All Articles