Skip to main content

Full Screen Youtube Video on Play - React

Youtube video is ubiquitous. Embedding Youtube videos into a web page is as straightforward as it sounds. What also seems natural is to full-screen the video on touching the play icon of the video on mobile devices. This feature is important for mobile user experience as the full screen control is quite small to "aim".

Google results on this topic showed many people had been looking for a solution on this and couldn't get a simple way to work out, as Youtube doesn't provide an API to full screen videos.

In this post, I am showing a relatively simply way to achieve this user experience with fairly few lines of code. Code example is shown below.

In the example, I use React as there are many nice plugins ready to start. Here is a list of them:
 import React from "react";  
 import screenfull from "screenfull";  
 import YouTube from "react-youtube";  
 import DeviceDetector from "device-detector-js";  
 import PropTypes from "prop-types";  
 import { makeStyles } from "@material-ui/core/styles";  
 export default function YTPlayer(props) {  
  const dd = new DeviceDetector();  
  const mobile = dd.usesMobileBrowser();  
  const fullScreen = event => {  
   var iframe = event.target.getIframe();  
   if (screenfull.isEnabled) {  
    screenfull.request(iframe);  
   }  
  };  
  const opts = {  
   height: "100%",  
   width: "100%",  
   controls: "1"  
  };  
  const useStyles = makeStyles({  
   videoDiv: {  
    width: "100%",  
    height: "100%"  
   }  
  });  
  const classes = useStyles();  
  return (  
   <YouTube  
    containerClassName={classes.videoDiv}  
    videoId={props.id}  
    opts={opts}  
    onPlay={() => (mobile ? fullScreen : {})}  
   />  
  );  
 }  
 YTPlayer.propTypes = {  
  id: PropTypes.string  
 };  

To use the above component, simply put the Youtube video id into it such as:

 <YTPlayer id="LjhCEhWiKXk" />  

Comments