Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  36] [ 4]  / answers: 1 / hits: 17921  / 6 Years ago, sun, august 19, 2018, 12:00:00

To set event listener say, onKeyPress listener on some react input element, we do something like this:



<SomeInputElement onKeyPress={this.someListener.bind(this)}>


Now, what should I do to make my someListener passive?


More From » html

 Answers
52

You can always add event listeners manually in componentDidMount using a reference to your element. And remove them in componentWillUnmount.



class Example extends Component {
componentDidMount() {
this.input.addEventListener('keypress', this.onKeyPress, { passive: false });
}

componentWillUnmount() {
this.input.removeEventListener('keypress', this.onKeyPress);
}

onKeyPress(e) {
console.log('key pressed');
}

render() {
return (
<SomeInputElement ref={ref => this.input = ref} />
);
}
}

[#53705] Tuesday, August 14, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;