I’ve been stuck on this for days (and read a lot of topics on here related to it) so I thought I should finally ask for a bit of help. I’m trying to build the drum machine but the onKeyPress element just isn’t working, it only plays the audio from the last clicked button.
I’ve set up a ref which I thought would’ve been the solution but still no luck, so any help would be much appreciated!
class DrumMachine extends React.Component {
constructor(props) {
super(props);
this.state = {
display: "Click or a press a key to play",
};
this.handleDisplay = this.handleDisplay.bind(this);
}
handleDisplay(display) {
this.setState({ display });
}
render() {
return (
<div id="drum-machine">
{drumSounds.map((drums) => (
<DrumPad
key={drums.id}
name={drums.name}
src={drums.audioLoc}
display={this.handleDisplay}
trigger={drums.trigger}
code={drums.code}
/>
))}
<div id="display">{this.state.display}</div>
</div>
);
}
}
class DrumPad extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.audio = React.createRef();
}
componentDidMount() {
document.addEventListener("keydown", this.handleKeydown);
window.focus();
}
componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeydown);
}
handleClick = (e) => {
this.audio.current.play();
this.audio.current.currentTime = 0;
};
handleKeyDown = (e) => {
this.audio.current.play();
this.audio.current.currentTime = 0;
};
render() {
return (
<div>
<div className="drum-pad" id={this.props.id}>
<button onClick={this.handleClick} onKeyPress={this.handleKeyDown}>
{this.props.trigger}
<audio
src={this.props.src}
id={this.props.name}
ref={this.audio}
></audio>
</button>
</div>
</div>
);
}
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36.
Challenge: Build a Drum Machine
Link to the challenge: