JSPM

react-native-websocket

1.0.2
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1855
  • Score
    100M100P100Q111330F
  • License MIT

WebSocket API wrapped as a component for React Native

Package Exports

  • react-native-websocket

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-native-websocket) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

react-native-websocket

Greenkeeper badge Package version Standard Travis Build GitHub version Dependency CI License

WebSocket API wrapped as a component for React Native

Table of Contents

About

If you're interested in using websockets in React Native generally here is a slightly abbreviated version of the source of this component:

class WS extends Component {
    //...
    send = (data) => this.state.ws.send(data)
    componentDidMount () {
        this.reconnect = !!this.props.reconnect
        this._handleWebSocketSetup()
    }
    componentWillUnmount () {
        this.reconnect = false
        this.state.ws.close()
    }
    _handleWebSocketSetup = () => {
        const ws = new WebSocket(this.props.url)
        ws.onopen = () => {
            this.props.onOpen && this.props.onOpen()
        }
        ws.onmessage = (event) => { this.props.onMessage && this.props.onMessage(event) }
        ws.onerror = (error) => { this.props.onError && this.props.onError(error) }
        ws.onclose = () => this.reconnect ? this._handleWebSocketSetup() : (this.props.onClose && this.props.onClose())
        this.setState({ws})
    }
}

As you can see the component simply wraps the native websocket api. It's also recommended that you implement your own exponential backoff reconnect logic if you plan on using this component in production.

Install

$ npm install --save react-native-websocket
# OR
$ yarn add react-native-websocket

Usage

import React, { Component } from 'react'
import { AppRegistry, View } from 'react-native'
import WS from 'react-native-websocket'

export default class Example extends Component {

  render () {
    return (
      <View style={{flex: 1}}>
        <WS
          ref={ref => {this.ws = ref}}
          url="wss://echo.websocket.org/"
          onOpen={() => {
            console.log('Open!')
            this.ws.send('Hello')
          }}
          onMessage={console.log}
          onError={console.log}
          onClose={console.log}
          reconnect // Will try to reconnect onClose
        />
      </View>
    )
  }
}

Contribute

Contributions are welcome. Please open up an issue or create PR if you would like to help out.

License

Licensed under the MIT License.