Altro
Altro

Reputation: 938

Youtube embed in react controls, play onclick

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.com/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)

Upvotes: 1

Views: 4559

Answers (1)

Shubham Verma
Shubham Verma

Reputation: 5054

You can pass url param in autoplay in youtube url:

like this

?autoplay=1

Here is complete code:

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

export default function App() {
  const [play, setPlay] = React.useState(false);
  const url = play
    ? `https://www.youtube.com/embed/tu-bgIg-Luo?autoplay=1`
    : `https://www.youtube.com/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

Upvotes: 7

Related Questions