Example of player integration in React.js


Example of a simple React application with player integration. The script is loaded with a hook (useEffect) and then initialized to the container.

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import Player from "./Player";
const rootElement = document.getElementById("root");
ReactDOM.render(
  <React.StrictMode>
    <App/>
    <Player id="player" file="https://plrjs.com/sample.mp4"/>
  </React.StrictMode>,
  rootElement
);

App.js

import { React, useEffect } from "react";
export default function App() {
  useScript("https://site.com/playerjs.js");
  return (
    <div className="App">
    <h1>Hello PlayerJS</h1>
    <input type="button" value="Play a new video" onClick={PlayNewVideo} />
    <div id="player"></div>
  );
}

function useScript(url) {
  useEffect(() => {
    const script = document.createElement("script");
    script.src = url;
    script.async = true;
    document.body.appendChild(script);
    return () => {
      document.body.removeChild(script);
    };
  }, [url]);
}

function PlayNewVideo() {
  if (window.pljssglobal.length > 0) {
    window.pljssglobal[0].api("play", "https://plrjs.com/new.mp4");
  }
}

The PlayNewVideo function shows how to launch a new link in the player via the API.

Player.js

export default function Player(config) {
  CreatePlayer(config);
  return "";
}

function CreatePlayer(config) {
  if (window.Playerjs) {
    new window.Playerjs(config);
  } else {
    if (!window.pjscnfgs) {
      window.pjscnfgs = {};
    }
    window.pjscnfgs[config.id] = config;
  }
}

window.PlayerjsAsync = function () {
  if (window.pjscnfgs) {
    Object.entries(window.pjscnfgs).map(([key, value]) => {
      return new window.Playerjs(value);
    });
  }
  window.pjscnfgs = {};
};

16.14.22022 © PlayerJS

Sign up free

Sign up
By signing up, you agree to Terms of Service
Login if you have an account

Restore password

Restore
Forgot email? Contact us