3

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, this clears up a lot of things. I'm gonna go test it out. One thing though, what is that event system you are using? I'm somewhat new to global events and all of that. I am currently using a name spaced global event system, and I have seen others using backbones event system. Is that a different event system?
I usually use node's EventEmitter. You can get it with var EventEmitter = require('events').EventEmitter, events = new EventEmitter() if you're using browserify or similar. There's also EventEmitter2 which you can easily get in npm or standalone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.