Reputation: 41
I want to create a HOC that have a event trigger when a certain key is pressed. When this key is pressed it should provide an event to the parent component. In this case, the key is "@".
Child HOC
import React, { Component } from 'react';
const withMention = WrappedComponent => {
return class extends Component {
state = {
mentionStart: false,
textInput: '',
selection: 0,
};
handleOnKeyPress = key => {
if (key === '@') {
this.setState({ mentionStart: true });
}
};
render() {
const { onMentionStart } = this.state;
return (
<WrappedComponent
onChangeText={text => {
this.setState({ textInput: text });
}}
onKeyPress={event => this.handleOnKeyPress(event.nativeEvent.key)}
onSelectionChange={event =>
this.setState({ selection: event.nativeEvent.selection })
}
onMentionStart={onMentionStart}
{...this.props}
/>
);
}
};
};
export default withMention;
Parent component
const UserComment = withMention(TextInput);
<UserComment onMentionStart={(event) => console.log(event)} />
I know the implementation is wrong, because whenever I assign a function to onMentionStart prop of child component in parent, child's function is overridden by parent. In this case, how to create a custom event trigger from child component and pass event into it so that the parent can use it accordingly?
Upvotes: 2
Views: 684
Reputation: 41
I actually solved it by removing onMentionStart prop from HOC and passed onMentionStart function from parent to child as a callback, handled it in onKeyPress handler function.
import React, { Component } from 'react';
const withMention = WrappedComponent => {
return class extends Component {
state = {
mentionStart: false,
textInput: '',
selection: 0,
};
handleOnKeyPress = key => {
if (key === '@') {
this.setState({ mentionStart: true }, () =>
this.props.onMentionStart(this.state.mentionStart),
);
}
};
render() {
return (
<WrappedComponent
onChangeText={text => {
this.setState({ textInput: text });
}}
onKeyPress={event => this.handleOnKeyPress(event.nativeEvent.key)}
onSelectionChange={event =>
this.setState({ selection: event.nativeEvent.selection })
}
{...this.props}
/>
);
}
};
};
export default withMention;
Upvotes: 2