How To Integrate Youtube Api Into React App
As a digital prototyping bureau, my company works with clients to aid them quickly test the cadre of their ideas with their clients and investors.
1 of our clients is a group of doctors exploring ways to assistance support older patients with mail service-operative care.
In that location are a number of strands to the application, just i is sharing exercises with patients and tracking their success. The exercises are hosted on YouTube and shared in a NextJS application.
Concluding week, nosotros got this asking from the product director:
Hey,
Can nosotros trigger a pop-upwardly to ask the patient if they completed the do? This should trigger when the video ends or is paused at more than nearly 95%.
Up to this bespeak, we were embedding the YouTube actor and non interacting with the API. This was going to be fun.
Exploring the documentation
The documentation for the YouTube Player API is very clear. I could see there were diverse event listeners and data properties available to explore. The slight issue I had was that information technology is written in a vanilla JavaScript prototype whereas I was working in React.
I've washed this kind of conversion earlier. Exploring the cosmos and passing of refs, the use of _document.js in NextJS to use external scripts and dealing with some of the idiosyncrasies that brand themselves known every bit y'all work through a project like this.
Before I dove in, I decided to have a wait for a React library that might handle all of this for me.
react-youtube library
Sometimes it is hard to discover the library you are looking for and sometimes it isn't. In this example, the description of this library seemed to exist exactly what I wanted:
Simple React component acting as a sparse layer over the YouTube IFrame Player API
I didn't find the documentation for the library very helpful but, since it claimed to exist a thin layer, I was hoping that I could lean on the YouTube documentation itself (spoiler alarm: I could!).
Laying out the projection
I was going to need:
- A modal and a way to rail its state;
- A function to convert a YouTube URL to the videoid that
react-youtubeneeds - A function to test if the video was at the target bespeak
- The
react-youtubeembed.
react-modal
I tend to enjoy projects that are named well and this is another 1 of those.
For some it may seem a bit overkill to utilise a library for modals, but I'one thousand a fan. Without a library like this, I'd take to build a lot of functionality myself (keyboard events, accessibility, clicking outside of the modal).
The documentation gives some decent default styles, so I'll add together these to the top of the project.
const modalStyles = { content: { top: "l%", left: "50%", correct: "automobile", bottom: "auto", marginRight: "-50%", transform: "translate(-50%, -50%)" } }; Inside my office, I'll add a useState hook to handle the status of the modal.
const [modalIsOpen, setModalIsOpen] = React.useState(false); Now I'g ready to add together my modal. I usually add this at the bottom of the component, but in reality you can add it wherever makes sense.
<Modal isOpen={modalIsOpen} onRequestClose={() => setModalIsOpen(false)} contentLabel="Practice Completed" style={modalStyles} > <div> <h3>Completed the do?</h3> <button onClick={handleExerciseComplete} > Complete exercise </button> </div> </Modal> A couple of things to notice:
- The isOpen prop takes the state value we created above.
- The onRequestClose is toggling that state value to faux. Yous could have a separate handle role just this seems a bit overkill.
- The mode prop is receiving the constant we created to a higher place.
Within the modal then, we are asking the question and providing a button to click if the patient has indeed completed it. I'1000 not going to explore what we are doing with the handleExerciseComplete function in the live code, so for now we'll just log to the console.
const handleExerciseComplete = () => console.log("Exercise something"); Preparing the videoID
The react-youtube library uses the videoID rather than the URL. Our content team are more comfy with URLs and I don't want to make life harder for them.
Normally, I'g sourcing this from a content management organisation, but for this example I'll add an input field with a useState to rails the value.
const [videoUrl, setVideoUrl] = React.useState(""); <input value={videoUrl} onChange={(eastward) => setVideoUrl(east.target.value)} /> Crawly! Now, nosotros need to be able to get the id from the URL. If yous've never looked at a YouTube URL in detail, it can look something like this https://www.youtube.com/watch?t=746&v=LRini_YIs2I&characteristic=youtu.be. The video id is the cord after v= and before the &.
A simpler form of the URL could look similar this https://world wide web.youtube.com/lookout?5=N1pIYI5JQLE and nosotros need to exist able to handle this, besides.
Here'southward my attempt at solving that problem.
let videoCode; if (videoUrl) { videoCode = videoUrl.split("v=")[ane].split("&")[0]; } Check elapsed fourth dimension
The YouTube API makes a lot of helper functions bachelor. The two that we're going to use are .getDuration() and .getCurrentTime().
We're going to utilize those two values to check if more 95% of the video has elapsed. If it has, we're going to trigger the modal to open up.
const checkElapsedTime = (east) => { const duration = eastward.target.getDuration(); const currentTime = eastward.target.getCurrentTime(); if (currentTime / elapsing > 0.95) { setModalIsOpen(true); } }; The e.target is equivalent to the player in the YouTube documentation. So, you tin can check out the docs to notice other ways to interact with the video for your project.
react-youtube
Now, we can finally add the YouTube component. We're going to use the onStateChange prop of the wrapper and pass our function down to information technology.
<YouTube videoId={videoCode} onStateChange={(e) => checkElapsedTime(eastward)} /> It feels slightly anti-climatic to see that now just we're done. We laissez passer the issue to our checkElapsedTime function and, if information technology passes the conditional, the modal will open.
There are a lot of other ways to hook into this API. The documentation lists the post-obit:
onReady={func} onPlay={func} onPause={func} onEnd={func} onError={func} onStateChange={func} onPlaybackRateChange={func} onPlaybackQualityChange={func} Each of these will accept a function like the one we have created above.
Try it out
I've prepare up a Code Sandbox with the case code from this article. Head over there and drop a YouTube URL into the input box. Test what happens every bit you move through the video and, in particular, when you pause or track to 95% or more.
Learn to code for gratuitous. freeCodeCamp'due south open source curriculum has helped more 40,000 people get jobs equally developers. Become started
Source: https://www.freecodecamp.org/news/use-the-youtube-iframe-api-in-react/
Posted by: haynesariervintend.blogspot.com

0 Response to "How To Integrate Youtube Api Into React App"
Post a Comment