plyr-react

repository·master·Indexed 19 days ago

https://github.com/chintan9/plyr-react

A responsive and accessible React wrapper for the Plyr media player (v6.0.0). It supports HTML5 video/audio, YouTube, and Vimeo through a simple <Plyr /> component and a usePlyr hook for advanced integrations, including HLS streaming. The library provides direct access to the underlying Plyr instance via React refs for programmatic control.

Tokens
2.7K
Snippets
9
Records
10
Agent score
18%

What's inside plyr-react

  1. Install peer dependencies for plyr-react

    master

    To use plyr-react, you must manually install its peer dependencies in your project. The required packages are react, react-dom, and plyr (version 3.7.7 or compatible).

    # NPM
    npm install react react-dom plyr
    
    # Yarn
    yarn add react react-dom plyr
    
    # PNPM
    pnpm add react react-dom plyr
  2. Install plyr-react

    master

    You can install plyr-react using NPM, Yarn, or PNPM.

    Note: Ensure you also install the required peer dependencies (react, react-dom, and plyr) to ensure the player functions correctly.

    # NPM
    npm install plyr-react
    
    # Yarn
    yarn add plyr-react
    
    # PNPM
    pnpm add plyr-react
  3. Integrate HLS streaming with usePlyr

    master

    For adaptive bitrate streaming, you can integrate libraries like hls.js by passing the HLS configuration into the usePlyr hook.

    Example pattern:

    <video
      ref={usePlyr(ref, {
        ...useHls(hlsSource, options),
        source,
      })}
      className="plyr-react plyr"
    />
  4. Use the <Plyr /> component for basic media playback

    master

    The <Plyr /> component is the simplest way to integrate a media player. You must import the plyr-react/plyr.css stylesheet to apply the default theme.

    Important CSS Path Change: As of v5.0.0, use plyr-react/plyr.css. For older versions (v4), use plyr-react/dist/plyr.css.

    import Plyr from "plyr-react"
    import "plyr-react/plyr.css"
    
    // Player source configuration
    const plyrProps = {
      source: {
        type: "video",
        sources: [
          {
            src: "https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4",
            type: "video/mp4",
            size: 720,
          },
        ],
        poster:
          "https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg",
      },
      options: {
        // Full list of options: https://github.com/sampotts/plyr#options
        controls: [
          "play-large",
          "play",
          "progress",
          "current-time",
          "mute",
          "volume",
          "captions",
          "settings",
          "pip",
          "airplay",
          "fullscreen",
        ],
      },
    }
    
    function MyPlayer() {
      return <Plyr {...plyrProps} />
    }
  5. Access the Plyr API via Refs

    master

    You can control the player instance programmatically by using a React ref. The ref.current.plyr object provides direct access to the underlying Plyr instance, allowing you to call methods like .play(), .pause(), or .fullscreen.enter().

    import React, { useRef, useEffect } from "react"
    import Plyr from "plyr-react"
    import "plyr-react/plyr.css"
    
    const PlayerController = () => {
      const ref = useRef(null)
    
      const playVideo = () => {
        // ref.current.plyr is the Plyr instance
        if (ref.current && ref.current.plyr) {
          ref.current.plyr.play()
        }
      }
    
      const enterFullscreen = () => {
        if (ref.current && ref.current.plyr) {
          ref.current.plyr.fullscreen.enter()
        }
      }
    
      return (
        <div>
          <Plyr
            ref={ref}
            source={{
              type: "video",
              sources: [{ src: "/path/to/video.mp4", type: "video/mp4" }],
            }}
          />
          <button onClick={playVideo}>Play</button>
          <button onClick={enterFullscreen}>Go Fullscreen</button>
        </div>
      )
    }
  6. Use the usePlyr hook for custom player integration

    master

    The usePlyr hook is recommended for advanced usage where you need full control over the player's lifecycle. It returns a ref that you can attach to a <video>, <audio>, or <div> element, allowing you to build completely custom component wrappers.

    import React from "react"
    import { usePlyr } from "plyr-react"
    import "plyr-react/plyr.css"
    
    // This example re-creates the <Plyr /> component using the hook
    const CustomPlyr = React.forwardRef((props, ref) => {
      const { source, options = null, ...rest } = props
    
      // usePlyr returns a ref that you can attach to a <video> or <div> element.
      const raptorRef = usePlyr(ref, {
        source,
        options,
      })
    
      return <video ref={raptorRef} className="plyr-react plyr" {...rest} />
    })
  7. Use the Plyr component

    master

    The Plyr component is a React wrapper around the Plyr media player. It renders a <video> element with the plyr-react plyr classes applied.

    To use it, provide a source (media source information) and optional options (Plyr configuration). You can also pass standard HTML video attributes (like controls, muted, etc.) directly to the component.

    To interact with the player instance from a parent component, use a ref with the type APITypes, which provides access to the underlying plyr instance.

    import { Plyr } from 'plyr-react';
    
    function MyPlayer() {
      const playerRef = React.useRef<APITypes>(null);
    
      // Access the player instance via playerRef.current.plyr
      const handlePlay = () => {
        playerRef.current?.plyr.play();
      };
    
      return (
        <Plyr
          ref={playerRef}
          source={{
            type: 'video',
            sources: [
              {
                src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4',
                type: 'video/mp4',
              },
            ],
          }}
          options={{...
        />
      );
    }
  8. Use the usePlyr hook

    master

    The usePlyr hook manages the lifecycle of a Plyr instance (instantiation, reconfiguration, and destruction) for a given video element.

    It is designed to be used when you need manual control over the video element's ref while still exposing the Plyr API to a forwarded ref.

    Parameters:

    • ref: A Ref<APITypes> that will receive the API object { plyr: PlyrInstance }.
    • params: A PlyrConfigurationProps object containing source and options.
    • deps (optional): A DependencyList. If not provided, the hook re-runs when params.options or params.source change.

    Returns:

    • A React.Ref<HTMLVideoElement> that must be attached to the <video> element.
    import { usePlyr, type APITypes } from 'plyr-react';
    
    function CustomPlayer() {
      const apiRef = React.useRef<APITypes>(null);
      const videoRef = React.useRef<HTMLVideoElement>(null);
    
      const playerParams = {
        source: { type: 'video', sources: [{ src: '...', type: 'video/mp4' }] },
        options: { ... }
      };
    
      // Connect the lifecycle to the video element
      const elementRef = usePlyr(apiRef, playerParams);
    
      return <video ref={elementRef} className="plyr" />;
    }
  9. Reference PlyrProps type

    master

    The PlyrProps type defines the configuration available to the Plyr component. It extends standard HTML video attributes while adding Plyr-specific configuration.

    Properties:

    • source: PlyrSource | null. The media source information (e.g., file URL, type).
    • options: PlyrOptions | null. Configuration object for the Plyr instance.
    • ...rest: Any valid VideoHTMLAttributes<HTMLVideoElement> (e.g., controls, autoPlay, muted, loop).
    type PlyrProps = Omit<ReactVideoProps, "ref"> & {
      source: PlyrSource | null;
      options?: PlyrOptions | null;
    };
  10. Reference APITypes and PlyrInstance types

    master

    When using ref with the Plyr component or the usePlyr hook, the API is exposed through the APITypes interface.

    APITypes Interface:

    • plyr: The PlyrInstance (the actual Plyr class instance).

    Type Aliases:

    • PlyrInstance: Represents the underlying plyr instance.
    • PlyrOptions: Represents the configuration options for Plyr.
    • PlyrSource: Represents the media source information.
    export interface APITypes {
      plyr: PlyrInstance;
    }
    
    export type PlyrInstance = Plyr.default;
    export type PlyrOptions = Plyr.Options;
    export type PlyrSource = Plyr.SourceInfo;