reactjstwitch

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?


Solution

  • 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')
    );