Created
January 2, 2017 19:56
-
-
Save jimthedev/7047c3258166fcfe83f2d47b835487ad to your computer and use it in GitHub Desktop.
Audio Player for React DOM with dynamic sources
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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