jifakir
jifakir

Reputation: 106

Why onKeyPress doesn't work for me in react?

I want to play the audio using ''onkeypress'' event:

import React, { useRef } from "react";

export default ({ source }) => {
  const audRef = useRef(null);
  const onPlayHandler = () => {
    audRef.current.play();
    console.log("Key pressed.");
  };
  return (
    <div tabIndex="1" className="drum-pad" onKeyPress={onPlayHandler}>
      <audio ref={audRef} className="clip" controls>
        <source src={source} type="audio/mpeg" />
        <source src={source} type="audio/ogg" />
      </audio>
      W
    </div>
  );
};

But it doesn't work for me.
Note: It works only after clicking the tab button but I want to play on any keypress and without using inside input tag. full code is here on codesandbox.

Upvotes: 1

Views: 1450

Answers (2)

Shubham Verma
Shubham Verma

Reputation: 5054

You can attach event listener to div you want to capture. But your code does not look like that requirement. Better way is to add event listener on dom mounted. You can do something like this:

import React, { useRef } from "react";

export default ({ source }) => {
  const audRef = useRef(null);

  React.useEffect(() => {
    window.addEventListener("keydown", onPlayHandler);
    return () => {
      window.removeEventListener("keydown", onPlayHandler);
    };
  },[]);
  const onPlayHandler = () => {
    console.log("Key pressed.");
    audRef.current.play();
  };
  return (
    <div tabIndex="1" className="drum-pad">
      <audio ref={audRef} className="clip" controls>
        <source src={source} type="audio/mpeg" />
        <source src={source} type="audio/ogg" />
        <source src={source} type="audio/wav" />
      </audio>
      W
    </div>
  );
};

Here is demo: https://codesandbox.io/s/purple-tdd-fe3e1?file=/src/DrumPad.js:0-672

Upvotes: 2

Veljko Blagojevic
Veljko Blagojevic

Reputation: 427

Short answer: Try with onKeyUp instead of onKeyPress

Long answer: some keys fire some of these events and don't fire others. For instance,

  • KeyPress ignores delete, arrows, PgUp/PgDn, home/end, ctrl, alt, shift etc while KeyDown and KeyUp don't (see details about esc below);
  • when you switch window via alt+tab in Windows, only KeyDown for alt fires because window switching happens before any other event (and KeyDown for tab is prevented by system, I suppose, at least in Chrome 71).

Upvotes: 0

Related Questions