Socket
Socket
Sign inDemoInstall

opentok-react

Package Overview
Dependencies
24
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    opentok-react

React components for OpenTok.js


Version published
Maintainers
1
Install size
5.23 MB
Created

Readme

Source

opentok-react

npm version Build Status

React components for OpenTok.js

Contents

Pre-Requisites

  1. NodeJS
  2. Register a TokBox account: https://tokbox.com/account/user/signup

Install

Add opentok-react as a dependency of your application:

yarn add opentok-react

Or if you're still using npm:

npm install --save opentok-react

Then include opentok.js before your application:

<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>

Alternatively, wrap your top-level component using OpenTok with the preloadScript HOC. The HOC will take care of loading opentok.js for you before rendering.

Example App

There is an example application provided in example/ and you can run it with the following steps:

  1. git clone https://github.com/aiham/opentok-react.git
  2. cd opentok-react/example/
  3. cp config.template.js config.js
  4. Edit config.js:
  5. Add your OpenTok API key, Session ID and Token (https://tokbox.com/account/)
  6. Add your Chrome Extension ID (https://tokbox.com/developer/guides/screen-sharing/js/)
  7. npm install
  8. npm run example
  9. Visit http://localhost:8000 in your browser

Refer to the App.js, Publisher.js and Subscriber.js files in example/components/ for library usage.

Usage

The following sections explains how to import and use opentok-react in your React application.

Importing opentok-react

Import the opentok-react components into your React application:

import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react';

Or require it if you need to use CommonJS modules:

const { OTSession, OTPublisher, OTStreams, OTSubscriber } = require('opentok-react');

Example with OTSession Component

class MyApp extends React.Component {
  render() {
    return (
      <OTSession apiKey="your-api-key" sessionId="your-session-id" token="your-session-token">
        <OTPublisher />
        <OTStreams>
          <OTSubscriber />
        </OTStreams>
      </OTSession>
    );
  }
}

Example with createSession Helper

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { streams: [] };
  }

  componentWillMount() {
    this.sessionHelper = createSession({
      apiKey: 'your-api-key',
      sessionId: 'your-session-id',
      token: 'your-session-token',
      onStreamsUpdated: streams => { this.setState({ streams }); }
    });
  }

  componentWillUnmount() {
    this.sessionHelper.disconnect();
  }

  render() {
    return (
      <div>
        <OTPublisher session={this.sessionHelper.session} />

        {this.state.streams.map(stream => {
          return (
            <OTSubscriber
              key={stream.id}
              session={this.sessionHelper.session}
              stream={stream}
            />
          );
        })}
      </div>
    );
  }
}

API Reference

The opentok-react library comprises of:

  • OTSession Component
  • OTPublisher Component
  • OTStreams Component
  • OTSubscriber Component
  • createSession Helper
  • preloadScript Higher-Order Component

OTSession Component

PropTypeRequiredDescription
apiKeyStringYesTokBox API Key
sessionIdStringYesTokBox Session ID
tokenStringYesTokBox token
eventHandlersObject<Function>NoEvent handlers passed into session.on
onConnectFunction()NoInvoked when session.connect successfully completes
onErrorFunction(err)NoInvoked when session.connect fails

OTPublisher Component

PropTypeRequiredDescription
sessionSessionNoOpenTok Session instance
propertiesObjectNoProperties passed into OT.initPublisher
eventHandlersObject<Function>NoEvent handlers passed into publisher.on
onInitFunction()NoInvoked when OT.initPublisher successfully completes
onPublishFunction()NoInvoked when session.publish successfully completes
onErrorFunction(err)NoInvoked when either OT.initPublisher or session.publish fail

The OTPublisher component will initialise a publisher and publish to a specified session upon mounting. You must specify a Session object using the session prop.

class MyApp extends React.Component {
  render() {
    return (
      <OTPublisher session={this.sessionHelper.session} />
    );
  }
}

Use the properties prop to specify a properties object for OT.initPublisher and the eventHandlers prop to specify an object of event handlers for Publisher#on.

class MyApp extends React.Component {
  constructor(props) {
    super(props);

    this.publisherProperties = {
      audioFallbackEnabled: false,
      showControls: false
    };

    this.publisherEventHandlers = {
      streamCreated: event => {
        console.log('Publisher stream created!');
      },
      streamDestroyed: event => {
        console.log('Publisher stream destroyed!');
      }
    };
  }

  render() {
    return (
      <OTPublisher
        session={this.sessionHelper.session}
        properties={this.publisherProperties}
        eventHandlers={this.publisherEventHandlers}
      />
    );
  }
}
TODO
  • Describe getPublisher() method.
  • Explain which properties OTPublisher will monitor for changes.
  • Explain that this component will not cause publisher to be appended to body.

OTStreams Component

PropTypeRequiredDescription
childrenOTSubscriberYesMust only have a single OTSubscriber component (or similar component that accepts session and stream props)
sessionSessionYesOpenTok Session instance. This is auto populated by wrapping OTStreams with OTSession
streamsArray<Stream>NoArray of OpenTok Stream instances. This is auto populated by wrapping OTStreams with OTSession

OTSubscriber Component

PropTypeRequiredDescription
sessionSessionNoOpenTok Session instance. This is auto populated by wrapping OTSubscriber with OTStreams
streamStreamNoOpenTok Stream instance. This is auto populated by wrapping OTSubscriber with OTStreams
propertiesObjectNoProperties passed into session.subscribe
eventHandlersObject<Function>NoEvent handlers passed into subscriber.on
onSubscribeFunction()NoInvoked when session.subscribe successfully completes
onErrorFunction(err)NoInvoked when session.subscribe fails

The OTSubscriber component will subscribe to a specified stream from a specified session upon mounting. You must provide a Stream object using the stream prop and a Session object using the session prop.

class MyApp extends React.Component {
  render() {
    return (
      <div>
        {this.sessionHelper.streams.map(stream => {
          return (
            <OTSubscriber
              key={stream.id}
              session={this.sessionHelper.session}
              stream={stream}
            />
          );
        })}
      </div>
    );
  }
}
TODO
  • Describe getSubscriber() method.
  • Describe properties prop.
  • Describe eventHandlers prop.
  • Explain which properties OTPublisher will monitor for changes.
  • Explain that this component will not cause subscriber to be appended to body.

createSession Helper

The createSession helper has been provided to easily create a session and monitor the current list of subscriber streams.

class MyApp extends React.Component {
  componentWillMount() {
    this.sessionHelper = createSession({
      apiKey: 'your-api-key',
      sessionId: 'your-session-id',
      token: 'your-session-token',
      onStreamsUpdated: streams => {
        console.log('Current subscriber streams:', streams);
      }
    });
  }

  componentWillUnmount() {
    this.sessionHelper.disconnect();
  }
}

The createSession helper returns an object with the following properties:

  • session - The Session instance.
  • streams - An up-to-date array of Stream instances.
  • disconnect - A clean up function. Call this when your component unmounts.

Use of this helper is optional and you can instead use the OTSession component or directly call OT.initSession and listen to streamCreated events if you prefer.

preloadScript Higher-Order Component

PropTypeRequiredDescription
opentokClientUrlStringNoThe URL of the OpenTok client script to load. It defaults to https://static.opentok.com/v2/js/opentok.min.js.
loadingDelegateElementNoAn element that will be displayed while the OpenTok client script is loading. It defaults to an empty <div />.

In larger applications, one might not want to load the opentok.js client with a <script> tag all the time. The preloadScript higher-order component will do this for you at the appropriate time.

For example, imagine you have a React Router application with the following route structure:

<Router>
  <Route path="/">
    <IndexRoute component="..." />
    <Route path="something" component="..." />
    <Route path="video" component={VideoChat} />
    <Route path="something-else" component="..." />
  </Route>
</Router>

What you'd like to do is delay the loading of opentok.js until the VideoChat component is being used. Here's how you can do this:

class VideoChat extends React.Component {
  // All the code of your component
}

export default preloadScript(App);

Custom Build

  1. git clone https://github.com/aiham/opentok-react.git
  2. cd opentok-react/
  3. npm install
  4. Modify code in src/
  5. npm run build
  6. Check that files in dist/ have been updated.

Contributing

If you make changes to the project that you would like to contribute back then please follow the contributing guidelines. All contributions are greatly appreciated!

Tests

Run the unit tests locally with the following command:

npm run unit

By default this will launch the Chrome browser. To run tests in Firefox use:

npm run unit -- --browsers Firefox

Run the linter with:

npm run lint

The unit tests are automatically run on Travis on both Chrome and Firefox and the current build status is shown at the top of this document.

Keywords

FAQs

Last updated on 31 Mar 2017

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc