hakunin hakunin - 1 year ago 121
React JSX Question

Passing child's events to a parent

I am enhancing a textarea with autocomplete functionality like this:

<MentionAutocomplete ref="autocomplete">
<Textarea ref="editor"/>

The idea is that
can use any thing like
in itself and still work.

This works nicely and its achieved by the autocomplete listening to keyboard events like this:


But I recently ran into an issue, where the autocomplete complains that
. I am assuming that the
component might be doing something, or there might be a browser extension messing with it.

So ideally I would like to do something like this:

var self = this;

<MentionAutocomplete ref="autocomplete">
<Textarea ref="editor" onKeyUp={(event) => self.refs.autocomplete.keyUp(event) } />

But I am wondering, is this the right approach? Is there a better way?

Answer Source

If I understand your issue correctly, you can define the event handler on the parent, and pass it through to the child:

<div className="MentionAutocomplete">
  {React.cloneElement(this.props.children {handleEvent: this.handleEvent})}

handleEvent here is a function you define on the parent where you can pass the event or whatever and is available on the child through this.props.

Another approach that seems a good fit for what you're trying to create would be to create a higher order component which essentially wraps a component with another to add functionality.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download