Reputation: 5198
I have a React Component rendering a html5 audio element like this (in the components render method)
<audio controls="controls" ref={(input) => {
input.onloadedmetadata = () => {
const duration = input.duration;
console.log("Duration: " + duration);
}
}}>
<source src={this.state.audiourl} type="audio/mpeg" />
</audio>
I need to access certain meta information of the audio file after it has been loading and having issues doing this.
As I understood it ref
would give me a reference to the DOM element and I could therefore attach a function to onloadedmetadata
. However this approach currently gives me the following error:
Uncaught TypeError: Cannot set property 'onloadedmetadata' of null
So input seems to be null. I have read that this is the currently advised appraoch to deal with refs and string refs are deprected.
Could somebody help me out?
Upvotes: 0
Views: 2917
Reputation: 16309
You should use react synthetic events for this. Just bind the event listener by passing it as a prop:
<audio
controls="controls"
onLoadedMetadata={event => console.log(event.target.duration)}
src={this.state.audiourl}
/>
Your error happens because react calls inline functions on the ref
prop first with null
and then with the DOM element ref. From the react docs:
If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases.
Upvotes: 3