I’m trying to generate <Audio>
components with map
:
import React, { useState, useRef, createRef } from 'react';
const audios = [{ src: '/fire.mp3' }, { src: '/crickets.mp3' }];
function Audio({ audioRef }) {
const { src, ref } = audioRef;
function handleVolumeChange(value) {
ref.current.volume = value / 100;
}
return (
<audio ref={ref} loop>
<source src={src} type="audio/mpeg" /> Your browser does not support the
audio element.
</audio>
// `handleVolumeChange` is used here
);
}
export const App = ({ name }) => {
const audioRefs = useRef(
audios.map((audio) => ({
...audio,
ref: createRef(),
}))
);
return (
<>
{audioRefs.current.map((audioRef, index) => (
<Audio key={audioRef.src} audio={audioRef} />
))}
</>
);
};
However, I’m getting this error:
Cannot destructure property ‘src’ of ‘audioRef’ as it is undefined.
Why is audioRef
undefined when audioRefs
is an array?
[{…}, {…}]
0: Object
ref: Object
src: "/fire.mp3"
<prototype>: Object
1: Object
ref: Object
src: "/crickets.mp3"
<prototype>: Object
Working code on StackBlitz.
Note: I need the ref to control the volume of the <audio>
element.
2
Answers
Presumably this is the line producing the error?:
In which case
audioRef
is a prop on theAudio
component here:Where do you use that
Audio
component? Here:As you can see, you’re not passing a prop called
audioRef
. You’re passing a prop calledaudio
(and akey
).The prop names need to match.
Either change the expected prop name to match what’s being passed:
Or change what’s being passed to match what’s expected:
You’ll need to use
React.forwardRef()
in<Audio />
to be able to forward to<audio>
.Small demo using 2 test
mp3
‘s from https://onlinetestcase.com/mp3-file/.Press the button to toggle the volume between the default
1.0
and0.2
.