How to add Kaltura video in your React or NextJs application
The video has become one of the very effective media platforms to reach out to the end user. And most of the content has been driven by some CMS like Drupal, WordPress, etc. It makes sense that a company would attempt to integrate video solutions into CMS, Kaltura will be the first solution. And times we are using a headless CMS-integrated solution and therefore adding video on various components or blocks become a bit challenging.
Many video solutions are available to integrate Kaltura video into the NextJs application, such as Auto embedded, Dynamic Embedded, and IFrame embeded. Most of the time Dynamic Embeded would be a good solution for integration as we can control the configuration dynamically.
Kaltura video integration samples are in the
Kaltura Developer guide. Check this out.
In this article, I will integrate the Kaltura video into a NextJS application, let's jump into code.
The sample HTML for video is like below -
Here is the video component sample code.
import { Suspense, useEffect, useState } from "react"
import * as cheerio from 'cheerio';
import Script from "next/script";
type Props = {
videoData: string
}
const KVideo = (props: Props) => {
const { videoData } = props
const [playerURL, setPlayerURL] = useState<string>()
const [UNIQUE_OBJ_ID, setUNIQUE_OBJ_ID] = useState<string>()
const [playerConfig, setPlayerConfig] = useState<any>()
useEffect(() => {
const parsedHTML = cheerio.load(videoData, { xmlMode: false })
const htmlElement: any = parsedHTML("script")
if (htmlElement.length === 2) {
const player = htmlElement[0].attribs.src
setPlayerURL(player)
try {
const playerConfiguration = JSON.parse((htmlElement[1].children[0].data.split("(")[1]).split(")")[0])
setPlayerConfig(playerConfiguration)
setUNIQUE_OBJ_ID(playerConfiguration.targetId)
} catch (error) {
console.error("can not parse player configuration")
}
}
}, [videoData])
if (!videoData) return <></>
return (
<>
{UNIQUE_OBJ_ID && playerURL &&
<Suspense fallback="<p>Loading...</p>">
<div id={UNIQUE_OBJ_ID} style={{ width: "100%", height: "20rem" }}></div>
<Script
id={`${UNIQUE_OBJ_ID}_${Math.floor((Math.random() * 100) + 1)}`}
src={playerURL} onLoad={() => {
// @ts-ignore
mw.setConfig("EmbedPlayer.DisableContextMenu", true)
// @ts-ignore
kWidget.embed(playerConfig)
}}
strategy="afterInteractive"
/>
</Suspense>
}
</>
)
}
export default KVideo;
Hope it helps you to integrate Kultura video in your NextJs site. Happy Coding!
-LP
Loading comments...