hakunin hakunin - 3 months ago 19
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"/>
</MentionAutocomplete>


The idea is that
MentionAutocomplete
can use any thing like
textarea
or
input
in itself and still work.

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

<div
className="MentionAutocomplete"
onKeyDown={this.handleKey}
onKeyUp={this.handleKeyUp}
>
{this.props.children}
{this.renderAutocomplete()}
</div>


But I recently ran into an issue, where the autocomplete complains that
field.value
is
undefined
. I am assuming that the
Textarea
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) } />
</MentionAutocomplete>


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

Answer

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})}
</div>

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.