Skip to content

Instantly share code, notes, and snippets.

@jimthedev
Created January 2, 2017 19:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimthedev/7047c3258166fcfe83f2d47b835487ad to your computer and use it in GitHub Desktop.
Save jimthedev/7047c3258166fcfe83f2d47b835487ad to your computer and use it in GitHub Desktop.
Audio Player for React DOM with dynamic sources
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
/**
* Use case: audio player with dynamic source in react
*
* Usage:
* <AudioPlayerDOM src={this.state.currentFile}/>
*
* Todo: make a better api, actually pass props through
* Todo: use children instead of passing
*/
export default class AudioPlayerDOM extends Component {
componentWillReceiveProps(nextProps) {
// Find some DOM nodes
const element = ReactDOM.findDOMNode(this);
const audio = element.querySelector('audio');
const source = audio.querySelector('source');
// When the url changes, we refresh the component manually so it reloads the loaded file
if ((nextProps.src) && (nextProps.src !== this.props.src)) {
// Change the source
source.src = nextProps.src;
// Cause the audio element to load the new source
audio.load();
}
}
render() {
return (
<div>
<audio controls>
<source src={this.props.src} />
</audio>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment