Plyr Video Player on Gatsby

I want to add plyr video player with selected options below to my gatsby blog. It takes video url from fetched json file. I just tried to add markdown it directly but it sometimes loading, sometimes not. Fetched url is changing from post to post.

Code

<video id="player" playsinline controls ></video>
<script src="https://cdn.plyr.io/3.6.4/plyr.js"></script>
<script>
var controls =['play-large', 'rewind','play','fast-forward','progress','current-time','duration','mute','volume','settings','pip', 'airplay','download','fullscreen'];
var player = new Plyr('#player', { controls });
fetch("test.url")
  .then(resp => resp.json())
  .then( data => {
    player.source = {
      type: 'video',
      title: data[0].label,
      sources: [
        {
          src: data[0].file,
          type: data[0].type,
          size: 720,
        },
      ],
    };
})
</script>

Json Data

[{"label":"Original","file":"link.mp4","type":"video\/mp4"}]

8 thoughts on “Plyr Video Player on Gatsby”

  1. I just tried to add markdown it directly but it sometimes loading,
    sometimes not

    You need to understand what’s going on. You are loading an external script (from a CDN: https://cdn.plyr.io/3.6.4/plyr.js) directly outside the scope of React and Gatsby. If the script has been loaded before you request it, it will work, otherwise, it won’t. Of course, things get odd in a production environment (gatsby build), where the codes behave slightly differently.

    If you are working in a React, you need to use a React-based dependency, in your case, react-plyr. Once you have installed it with:

    npm install react-plyr --save
    

    You can simply use it by:

    import Plyr from 'react-plyr';
    
    const IndexPage =()=>{
    
      return (
        <Plyr
          type="youtube" // or "vimeo"
          videoId="CDFN1VatiJA"
        />
      )
    }
    

    Note: The videoId can either be the video ID or URL for the media.

    At this point, you can choose the JSON or the markdown approach, what makes you feel comfortable. The important thing is to get the videoId parameter (the source) from each approach.

    Here’s a detailed article using Plyr + Gatsby: https://chaseohlson.com/plyr-gatsby-youtube-vimeo

    Reply

Leave a Comment