reactjsnext.jsaddeventlistenerkeydownjs-scrollintoview

eventListener callback function for keydown triggered twice


I have a menu at the right side and related description at the left and I want to change selected item in the menu when I press arrowDown or arrowUp keys. but every time I press the key the callback function triggered twice and scroll two by two not one by one!! I do't know whats wrong with my code.

I defined an event listener in componentDidMount like this:

public componentDidMount () {
 global?.window && global?.document.addEventListener('keydown', e => this.handleKeyPress(e));
}

and the callBack:

private handleKeyPress = (event: KeyboardEvent) => {
    const {activeType} = this.state;
    const {allSolutions} = this.props;

    const index = allSolutions.findIndex(x => x === activeType);
    if (event.key === 'ArrowDown') {
      this.scrollToSolutions(allSolutions[index + 1]);
    } else if (event.key === 'ArrowUp') {
      this.scrollToSolutions(allSolutions[index - 1]);
    }
  }

scrollToSolution:

private scrollToSolutions = (id?: number) => {
    const item = document.getElementById(id?.toString() ? id.toString() : '');
    this.setState({activeType: id});
    if (item) {
      item.scrollIntoView({block: 'center'});
    }
}

thanks for any suggestions.


Solution

  • Ensure that componentDidMount is not being called more than once, as this would add multiple event listeners. you have a typo in the lifecycle method name (componenDidMount should be componentDidMount). If the name is incorrect, the method won't be called as a lifecycle method, and if it's called manually somewhere else in your code, it could lead to multiple event listeners.