import React, {useState, useRef, useEffect} from 'react'
import Toggle from './Toggle';
function App() {
const [sound, setSound] = useState("sound track name")
const datas = [
{
key: 'Q',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Heater-1.mp3",
name: "Heater_1"
},
{
key: 'W',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Heater-2.mp3",
name: "Heater_2"
},
{
key: 'E',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Heater-3.mp3",
name: "Heater_3"
},
{
key: 'A',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Heater-4_1.mp3",
name: "Heater_4"
},
{
key: 'S',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Heater-6.mp3",
name: "Clap"
},
{
key: 'D',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Dsc_Oh.mp3",
name: "Open-HH"
},
{
key: 'Z',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Kick_n_Hat.mp3",
name: "Kick-n'-Hat"
},
{
key: 'X',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/RP4_KICK_1.mp3",
name: "Kick"
},
{
key: 'C',
url: "https://cdn.freecodecamp.org/testable-projects-fcc/audio/Cev_H2.mp3",
name: "Closed-HH"
}
]
const audioSrc = useRef("")
function handleKeys(event) {
const currentKey = datas.find(data => event.key.toUpperCase() === data.key)
console.log(currentKey);
currentKey.name ? setSound(currentKey.name) : console.log('this key is unable');
audioSrc.current.src = currentKey.url
if (audioSrc.current) {
audioSrc.current.play();
}
}
window.addEventListener('keydown', handleKeys)
const playAudio = (link, name) => {
name ? setSound(name) : setSound("something is wrong")
audioSrc.current.src = link
if (audioSrc.current) {
audioSrc.current.play();
}
else {
console.log('not working');
}
};
return (
<div className="bg-black h-[100vh] w-[100vw] flex items-center justify-center" >
<div className=" flex felx-row rounded-e-mdxl h-[50vh] w-[60vw] bg-gray-600">
<div className="flex flex-wrap gap-4 p-4 h-[100%] w-[60%]" id='drum-machine'>
{
datas.map(data => {
return (
<button key={data.key} id='display' className='bg-blue-500 rounded-lg text-white p-2 w-1/4 drum-pad' onClick={() => playAudio(data.url, data.name)}>{data.key}
<audio ref={audioSrc} key={data.key} className='clip' id={data.key} src={data.url}></audio>
</button>
)
})
}
</div>
<div className="flex flex-col justify-evenly items-center h-[100%] w-[40%]">
<Toggle forId="power"/>
<p className='h-8 w-19 bg-gray-50'>{sound}</p>
<input className='w-[80%] cursor-pointer' type="range" />
<Toggle forId="bank" />
</div>
</div>~
</div>
)
}
export default App
please provide all code needed to build the app and how to reproduce the issue
You can’t use a single ref with a map. You can use a ref callback with an array or a Map
You could also just use a plain DOM method to get the audio element.
The DX for using refs with maps isn’t all that great.