VicenteC
VicenteC

Reputation: 422

Reactjs How to use properly onKeyDownCapture?

I'm using onWheelCapture to detect the scroll offset from the top. As I'm using onWheelCapture, it only detects the movement when the user scrolls up or down. I would like to detect the scroll offset when the user presses the key-down or space key. So I tried to use onKeyDownCapture in order to listen to when using the keyboard but it doesn't work. I also tried it with onKeyPressCapture but it doesn't work either. This was checked using the console, it only prints the distance from the top when scrolling.

    <React.Fragment>

    <main className={classes.Content}  
        onWheelCapture={props.onScrollMethod}   //This one works
        onKeyPressCapture={props.onScrollMethod}    //This one doesn't work
        onKeyDownCapture={props.onScrollMethod} >     //This one doesn't work either
        <div className={classes.ContentWrapper}>
            {props.children}
        </div>
    </main> 
</React.Fragment>

Am I missing something? Thank you in advance for your time and help!

Upvotes: 0

Views: 2153

Answers (1)

pilchard
pilchard

Reputation: 12909

Non interactive elements need to have tabIndex set in order to be able to listen for these events. Discussed here: onKeyDown event not working on divs in React.

Working code snippet, but you need to focus the gray div to see the events logged.

function CaptureComp() {

  const keyHandler = (e) => {
    console.log(e.altKey,
      e.charCode,
      e.ctrlKey,
      e.key,
      e.keyCode,
      e.ctrlKeylocale,
      e.location,
      e.metaKey,
      e.repeat,
      e.shiftKey,
      e.which)  
  }

  return (
    <div className="container"
      onKeyDownCapture={keyHandler}
      onKeyPressCapture={keyHandler}
      onKeyUpCapture={keyHandler}
      tabIndex="-1"
      >
            <p>Event Container</p>
    </div> 
  );
}

ReactDOM.render(<CaptureComp />, document.getElementById('App'));
body {
  margin:0;
  padding:0;
}
.container {
  width: 100vw;
  height: 100vh;
  background-color: gray;
 }
 p {
  text-align:center;
  padding:4rem;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="App"></div>

Upvotes: 1

Related Questions