Craig Lu
Craig Lu

Reputation: 25

Using Twitch Embedded Video with ReactJS

I've been creating a personal project and trying to use the Twitch Embedded API to display Twitch streams and the chat within my web page. I have some experience with ReactJS but I'm not sure how to handle this situation at the moment.

Here is the HTML of how one would embed a twitch stream from the Twitch API docs:

<html>
  <body>
    <!-- Add a placeholder for the Twitch embed -->
    <div id="twitch-embed"></div>

    <!-- Load the Twitch embed script -->
    <script src="https://embed.twitch.tv/embed/v1.js"></script>

    <!-- Create a Twitch.Embed object that will render within the "twitch-embed" root element. -->
    <script type="text/javascript">
      new Twitch.Embed("twitch-embed", {
        width: 854,
        height: 480,
        channel: "monstercat"
      });
    </script>
  </body>
</html>

What is the best way to accomplish this while using React?

Upvotes: 1

Views: 5686

Answers (3)

hooleymcknight
hooleymcknight

Reputation: 41

Using a functional component instead of a class component, here's how I got mine to work in a way that I can show/hide players based on whether or not they're online or offline. This also works if you have several channels you're going to iterate through, you can just pass in the channel name through props.

I'm using state and an extra check for iframes so extra event listeners/iframes don't get added in. Of course you'll want to add in css for the hide class.

import { useState, useEffect } from 'react'

export default function LiveNowSingle(props) {
  const [embed, setEmbed] = useState(null)

  useEffect(() => {
    if (embed) {
      embed.addEventListener(Twitch.Player.ONLINE, () => {
        console.log('online!')
        document.querySelector(`#twitch-${props.channelName}`).classList.remove('hide')
      })
  
      embed.addEventListener(Twitch.Player.OFFLINE, () => {
        console.log('offline!')
        document.querySelector(`#twitch-${props.channelName}`).classList.add('hide')
      })
    }
    else if (!document.querySelector(`#twitch-${props.channelName} iframe`)) {
      setEmbed(new Twitch.Player(`twitch-${props.channelName}`, {
        width: 650,
        height: 340,
        channel: props.channelName
      }))
    }
  }, [embed])
  
  return (
    <div id={`twitch-${props.channelName}`} className="hide">
      {props.channelName}
    </div>
  )
}

Upvotes: 0

Takumi Adachi
Takumi Adachi

Reputation: 88

Running code: https://jsfiddle.net/tadachi/7jzfnw99/8/

Since twitch doesn't supply npm packages for their twitch embeds and you want to be able to be as react-like as possible, I created an element that supplies the external twitch script, put it in onComponentMount(), then render it.

const EMBED_URL = 'https://embed.twitch.tv/embed/v1.js';

class Hello extends React.Component {
    componentDidMount() {
    let embed;
    const script = document.createElement('script');
    script.setAttribute(
      'src',
      EMBED_URL
    );
    script.addEventListener('load', () => {
      embed = new window.Twitch.Embed(this.props.targetID, { ...this.props });
    });
        document.body.appendChild(script);
  }

  render() {

    return (
        <div>
        Hello {this.props.targetID} {this.props.width} {this.props.height}
        <div id={this.props.targetID}>test</div>
      </div>
    )
  }
}

Hello.defaultProps = {
    targetID: 'twitch-embed',
    width: '940',
  height: '480',
}

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

Upvotes: 2

Uchit Kumar
Uchit Kumar

Reputation: 677

This answer is highly generic ... just one possible way.. hope this atleast gives you a direction. You can post your react code where you tried to implement it ..I will update my answer

To use this there is three main part.

  1. load twitch js file
  2. create element to embed video in your case element with id twitch-embed
  3. call twitch function for initialization and settings

For 1 You can load twtich js file in your html file .. mainly index.html. or you can import or require it ... based on your react tech stack. For second .. you can add <div id=twitch-embed ></div> in your component

for third.. you can call this function in componentDidMount() lifecycle hook of react component.

Upvotes: 0

Related Questions