For our app we’re going to be using the
Mixcloud Javascript widget library to control our
audio player and listen in to some of the events that occur with it.
First off, we need to add the libary to our index.html
, which lives inside the public
folder:
<script src="//widget.mixcloud.com/media/js/widgetApi.js"></script>
Now we can make use of the widget library inside of our App.js
component. The aim is to set up
some methods/actions that interact with it, doing things like playing a new mix and pause/playing
the music.
We first have to initalize things by passing our audio iframe
into the library. To do that we need
a ref
on our iframe so we can access the actual html element. Let’s call it this.player
:
return (
<iframe
className="player db fixed bottom-0"
ref={player => (this.player = player)}
width="100%"
height="60"
src="https://www.mixcloud.com/widget/iframe/?hide_cover=1&mini=1&feed=%2FNTSRadio%2Ffloating-points-jamie-xx-18th-august-2016%2F"
frameBorder="0"
/>
)
With that in place let’s set up a method in our App
component called mountAudio
. It’s going to
be an async
function that takes our iframe
and lets us do things with it like play new mixes or
play/pause the audio:
mountAudio = async () => {
this.widget = Mixcloud.PlayerWidget(this.player)
await this.widget.ready
}
Our page will now throw an error about Mixcloud
not being defined. This is because we’re not using
it as a module and it’s coming outside of React in our index.html
file. To get around this we need
to add this rule at the top of our App.js
file to tell it to stop complaining:
With our mountAudio
method, we can run it when our component is ready on the page by using one of
React’s lifecycle methods. We’ll use componentDidMount
to run things when the component’s mounted
and ready on the page.
componentDidMount() {
this.mountAudio();
}