Sunday, July 10, 2022

[FIXED] How can I send an audio reference to a function in React?

Issue

I have an audio reference:

    const sound1 = useRef();

as I made it by:

   <audio  ref={sound1} src='/resources/DRUMS.mp3' loop={looping}></audio>

and a function I wnat to send it to:

const toggleMuteUnmute=(soundRef, isPlaying, stateFunc)=>{
    const prevValue = isPlaying;
    stateFunc(!prevValue);
    if(prevValue){
        soundRef.current.muted = false;
        animationRef.current = requestAnimationFrame(whilePlaying);
    }
    else{
        soundRef.current.muted = true;
        cancelAnimationFrame(animationRef.current);
    }
}

using this:

<button onClick={toggleMuteUnmute(sound1, isPlaying1, setIsPlaying1)} >

but an error comes up:

Cannot set properties of undefined (setting 'muted')

reffering to the first line in the 'else' statement.

Why can't it read the muted attribute of the html audio tag?


Solution

Ok I solved it. All I had to do was to put - () => before the function call, as in -

<button onClick={() => toggleMuteUnmute(sound1, isPlaying1, setIsPlaying1)} >


Answered By - Nadav Holtzman
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.