|
| 1 | +import { useState } from 'react'; |
| 2 | +import YouTube, { YouTubePlayer } from 'react-youtube'; |
| 3 | +import type { NextPage } from 'next'; |
| 4 | +import Head from 'next/head'; |
| 5 | + |
| 6 | +const VIDEOS = ['XxVg_s8xAms', '-DX3vJiqxm4']; |
| 7 | + |
| 8 | +const Home: NextPage = () => { |
| 9 | + const [player, setPlayer] = useState<YouTubePlayer>(); |
| 10 | + const [videoIndex, setVideoIndex] = useState(0); |
| 11 | + const [width, setWidth] = useState(600); |
| 12 | + const [hidden, setHidden] = useState(false); |
| 13 | + const [autoplay, setAutoplay] = useState(false); |
| 14 | + |
| 15 | + return ( |
| 16 | + <div id="app"> |
| 17 | + <Head> |
| 18 | + <title>react-youtube example ssr</title> |
| 19 | + </Head> |
| 20 | + <div style={{ display: 'flex', marginBottom: '1em' }}> |
| 21 | + <button type="button" onClick={() => player?.seekTo(120, true)}> |
| 22 | + Seek to 2 minutes |
| 23 | + </button> |
| 24 | + <button type="button" onClick={() => setVideoIndex((videoIndex + 1) % VIDEOS.length)}> |
| 25 | + Change video |
| 26 | + </button> |
| 27 | + <label> |
| 28 | + <input |
| 29 | + type="range" |
| 30 | + min="300" |
| 31 | + max="1080" |
| 32 | + value={width} |
| 33 | + onChange={(event) => setWidth(event.currentTarget.valueAsNumber)} |
| 34 | + /> |
| 35 | + Width ({width}px) |
| 36 | + </label> |
| 37 | + <button type="button" onClick={() => setHidden(!hidden)}> |
| 38 | + {hidden ? 'Show' : 'Hide'} |
| 39 | + </button> |
| 40 | + <label> |
| 41 | + <input type="checkbox" checked={autoplay} onChange={(event) => setAutoplay(event.currentTarget.checked)} /> |
| 42 | + Autoplaying |
| 43 | + </label> |
| 44 | + </div> |
| 45 | + |
| 46 | + {hidden ? ( |
| 47 | + 'mysterious' |
| 48 | + ) : ( |
| 49 | + // @ts-ignore |
| 50 | + <YouTube |
| 51 | + videoId={VIDEOS[videoIndex]} |
| 52 | + opts={{ |
| 53 | + width, |
| 54 | + height: width * (9 / 16), |
| 55 | + playerVars: { |
| 56 | + autoplay: autoplay ? 1 : 0, |
| 57 | + }, |
| 58 | + }} |
| 59 | + className="container" |
| 60 | + onReady={(event) => setPlayer(event.target)} |
| 61 | + /> |
| 62 | + )} |
| 63 | + </div> |
| 64 | + ); |
| 65 | +}; |
| 66 | + |
| 67 | +export default Home; |
0 commit comments