Front End Development Libraries Projects - Build a Drum Machine

Tell us what’s happening:

Currently the only non-functional portion of my project is getting the audio to play when the respective buttons are clicked on. When I click on a button, I get an uncaught type error “Cannot read properties of null (reading ‘play’)”, and I’m not sure why my audio element would be null here.

Your code so far

function DrumButton(props) {

const audio = document.getElementById(props.hotkey)

function handleClick() {
console.log(audio)
audio.play()
}
//…other functions
return (
<div className=‘drum-button’ style={{backgroundColor: props.color}} onClick={handleClick} onKeyDown={handleKey}>
<p className='hotkey'>{props.hotkey.toUpperCase()}</p>
<audio id={props.hotkey} className='clip'>
<source src={props.path} type='audio/mpeg'/>
</audio>
</div>
)
}

Creating a DrumButton looks like this, if it helps:
<DrumButton color='red' hotkey='q' path='https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'></DrumButton>

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Update: Looks like I’ve just fixed it by declaring the audio variable within handleClick rather than outside of it. Though if anyone knows the particular reason as to why this fixed the issue, I’d still like to know!