Using Clappr with ReactJS

Mike Griffith
2 min readJun 3, 2016

--

Clappr is an awesome HLS media player for the web. One of its major selling points is that it uses hls.js to provide MSE-based playback for browsers that support it, while housing other playback engines when needed (native HLS for Safari, Flash for really old browsers). It also provides a nice out-of-the-box UI skin for the media controls and has a reasonable plugin architecture to extend it.

However, due to its internal rendering architecture and ReactJS’ demands, Clappr does not readily drop into a ReactJS project.

Building a ClapprPlayer React Component

In order to get a Clappr component running in your ReactJS project, you’ll need to break the component tree. This is because Clappr will mutate its sub-DOM outside of React’s control, which causes React to issue an Invariant Violation.

A simple trick to break the tree (often used when embedding jQuery plugins inside React) is to always return false from the `shouldComponentUpdate` React lifecycle method — this tells React to stop looking at this part of the DOM tree. React will then gladly become oblivious to Clappr’s DOM manipulations

A simple `ClapprPlayer` component then could look like this:

We’ve specified a few hardcoded options to Clappr, but you can imagine building out your component to support the numerous Clappr options and passing them through as React props.

Now we can easily drop in a player into our normal component tree in a React project.

Custom Clappr Plugins

Where it gets even funner is now building out custom Clappr plugins inside your ReactJS project. Clappr plugins are registered through the player options and are given an opportunity to affect the DOM inside the player widget. Most Clappr plugins use some helper methods to pull together HTML and CSS templates with a bit of javascript logic in a controller. But the React JSX syntax is appealing for custom media control elements.

Remember, we’ve already broken the React component tree inside Clappr, so to make a plugin in React-style, we’ll need to re-render using ReactDOM.

A simple plugin that adds a dummy button to the media control bar might look like this:

Registering this would be as simple as importing this file into your original ClapprPlayer component and adding a Clappr option with `plugins: { core: [ClapprReactSettingsPlugin]}`.

Now you can imagine building out an entire component tree instead of the simple `MyComponent`. You can pass functions as props to the components, giving callbacks to trigger events that have access to Clappr or hls.js internals as needed.

Hopefully this has gotten the wheels turning a bit. We’ve been able to build out some pretty interesting and useful plugins starting with this pattern. Let me know what you dream up!

--

--

Mike Griffith

Software engineer, big dreamer, and rider of two wheelers. Raising three awesome kiddos with my amazing wife. Working @BoxCast