Skip to main content

ReactJS

To add the Lura Player to your ReactJS component, you need to load the player script and then create an instance of the player using JavaScript. Here's how:

1. Create a ReactJS App

npx create-react-app lura-player-demo-app

2. Change current working directory to lura-player-demo-app

cd lura-player-demo-app/

3. Make a components directory

mkdir src/components

4. Create a new LuraPlayerComponent.jsx file in components.

lura-player-demo-app/src/components/LuraPlayerComponent
import React, { useEffect, useRef, useState } from "react";

export default function LuraPlayerComponent({
config,
onPlayerLoaded,
...others
}) {
const ref = useRef(null);
const [player, setPlayer] = useState(null);
const [scriptResolved, setScriptResolved] = useState(false);

useEffect(() => {
onPlayerLoaded && onPlayerLoaded(player);
}, [onPlayerLoaded, player]);

useEffect(() => {
const scriptPromise = new Promise((res, rej) => {
const script = document.createElement("script");
script.src =
"https://w3.mp.lura.live/lura-player/web/latest/lura-player.js";
script.onload = () => {
res();
};
document.body.appendChild(script);
}).then(() => {
setScriptResolved(true);
});
// eslint-disable-next-line no-unused-expressions
scriptPromise;
}, []);

useEffect(() => {
if (ref && ref.current && !player && config && scriptResolved) {
if (!ref.current) {
return;
}
const luraPlayer = new lura.Player(ref.current);
luraPlayer.setConfig(config);
setPlayer(luraPlayer);
}

return () => {
if (player) {
player.destroy();
}
};
}, [config, player, ref, scriptResolved, setPlayer]);

return <div ref={ref} {...others}></div>;
}

5. Now use the LuraPlayerComponent in your App.js

lura-player-demo-app/src/App.js
import "./App.css";
import LuraPlayerComponent from "./components/LuraPlayerComponent";
import { useEffect, useState } from "react";

function App() {
const [player, setPlayer] = useState(null);
useEffect(() => {
window.player = player;
}, [player]);
return (
<div className="App">
<header className="App-header">
<LuraPlayerComponent
onPlayerLoaded={setPlayer}
style={{
width: "640px",
height: "360px",
}}
config={{
lura: {
appKey:
"PqSpQb9pFu1A_v4qrMnRNwcXJGoFMO0B02BwGBQ4Zwa0_uMdXPXrqjnlSbJbkv8duDNk2-c3JbOXq2auBscWP1GyvlWlgFcIzaO6QFG74nY",
assetId: "5179686",
},
}}
/>
</header>
</div>
);
}

export default App;

Note that you need to replace the placeholder value for the "config" property with your own Lura Player config.

6. Run the ReactJS app by executing:

npm run start

That's it! You should now see the Lura Player embedded in your ReactJS component.