benwiley4000 / cassette

📼 A flexible media player component library for React that requires no up-front config
https://benwiley4000.github.io/cassette/styleguide
MIT License
185 stars 28 forks source link

mediaElementRef Help #346

Closed steveambielli closed 5 years ago

steveambielli commented 5 years ago

In version 1 I was using onMediaEvent for when the player was paused, etc. What would the correct syntax be for mediaElementRef? In the component I have mediaElementRef={elem => this.audioElement = elem }. Thanks!

benwiley4000 commented 5 years ago

Hey Steve, if you want the quickest fix you can do this:

<MediaPlayer
  playlist={myPlaylist}
  mediaElementRef={elem => {
    elem.addEventListener('play', () => console.log('PLAY'));
    elem.addEventListener('pause', () => console.log('PAUSED'));
  }}
/>

However in version 2 the recommended way is to surround the entire section of your app that needs access to this state with a PlayerContextProvider. So it could look like this:

import { PlayerContextProvider, PlayerContextConsumer } from '@cassette/core';
import { MediaPlayerControls } from '@cassette/player'; 

function MyApp() {
  return (
    <PlayerContextProvider playlist={myPlaylist}>
      <div>
        <PlayerContextConsumer>
         {playerContext => <PausedCheck isPaused={playerContext.paused} />}
        </PlayerContextConsumer>
      </div>
     <MediaPlayerControls />
    </PlayerContextProvider>
  );
}

function PausedCheck({ isPaused }) {
  return isPaused ? 'Media is paused' : 'Media is playing';
}

The <div /> is just there to demonstrate that the Consumer doesn't need to be a direct child of the Provider. The Provider can wrap your whole app if you only need to play one playlist.

There's also the playerContextFilter higher-order-component that lets you do this:

import { PlayerContextProvider, playerContextFilter } from '@cassette/core';
import { MediaPlayerControls } from '@cassette/player';

function MyApp() {
  return (
    <PlayerContextProvider playlist={myPlaylist}>
      <div>
        <PausedCheck />
      </div>
     <MediaPlayerControls />
    </PlayerContextProvider>
  );
}

function PausedCheck({ paused }) {
  return paused ? 'Media is paused' : 'Media is playing';
}
PausedCheck = playerContextFilter(PausedCheck, ['paused']);
benwiley4000 commented 5 years ago

Not sure if you've found the docs website for Cassette v2, but it's here: https://benwiley4000.github.io/cassette/styleguide

Please let me know if you run into any other questions or other issues! The docs are still in progress and need some work. I'd appreciate any help making them better.

benwiley4000 commented 5 years ago

Hey @steveambielli - could you let me know if you solved your problem?

benwiley4000 commented 5 years ago

Closing for now - let me know if you have other questions. :slightly_smiling_face: