admin管理员组

文章数量:1391937

I have an iframe with a youtube video and a button, I want to play youtube video on button click

this is my code

<iframe width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<button>Play</button>

I have an iframe with a youtube video and a button, I want to play youtube video on button click

this is my code

<iframe width="560" height="315" src="https://www.youtube./embed/tu-bgIg-Luo" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<button>Play</button>

Thanks

P.S. I am using react so the solution I need in react or in HTML/CSS/JS (Not a jQuery please)

Share asked Aug 31, 2020 at 8:32 AltroAltro 9483 gold badges11 silver badges28 bronze badges 2
  • 1 Youtube API developers.google./youtube/iframe_api_reference – Alexander Kiselev Commented Aug 31, 2020 at 8:37
  • I couldn't find any useful information there eligible for react, maybe I am searching bad but I searched for about an hour :/ – Altro Commented Aug 31, 2020 at 8:54
Add a ment  | 

1 Answer 1

Reset to default 7

You can pass url param in autoplay in youtube url:

like this

?autoplay=1

Here is plete code:

import React from "react";
import "./styles.css";

export default function App() {
  const [play, setPlay] = React.useState(false);
  const url = play
    ? `https://www.youtube./embed/tu-bgIg-Luo?autoplay=1`
    : `https://www.youtube./embed/tu-bgIg-Luo`;
  return (
    <div className="App">
      <iframe
        width="560"
        height="315"
        src={url}
        frameborder="0"
        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
        allowfullscreen
      ></iframe>
      <button onClick={() => setPlay(true)}>Play</button>
    </div>
  );
}


Here is the demo: https://codesandbox.io/s/serene-yonath-9z2hs?file=/src/App.js:0-556

本文标签: javascriptYoutube embed in react controlsplay onclickStack Overflow