How to render a value stored with useRef?


I have this code in my React component:

const audio = useRef(new Audio(song));

when I console.log(audio.current) this is the result:

<audio id="beep" preload="auto" src="/static/media/ding-sound.ab26721d1e2926a00214.mp3">

The result is a HTML audio tag with id, preload and src attributes.

Here comes my problem.

In my render method I have:


However, the audio element doesn’t render and the console shows this error "Objects are not valid as a React child (found: [object HTMLAudioElement]).

Any ideas how to render audio.current?

I tried also with audio.current.outerHTML, but then it renders as a string.

You can render HTML directly in react using dangerouslySetInnerHTML, that will do :slight_smile:

Remember to check that ref.current holds a value, before attempting to do anything, just a tip to avoid runtime errors :slight_smile:

Hope this helps.

1 Like

I haven’t thought about that. Thank you very much.
I am away from my computer, but I will try it once I come back.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.