0.0.11 • Published 5 years ago

react-mqtt v0.0.11

Weekly downloads
14
License
MIT
Repository
github
Last release
5 years ago

Build Status

mqtt-react

React Container for mqttjs/MQTT.js

Demo

There is a very minimalistic Demo-App: mqtt-react-demo

Usage

Currently, mqtt-react exports two enhancers. Similarly to react-redux, you'll have to first wrap a root component with a Connector which will initialize the mqtt instance and then subscribe to data by using subscribe.

Root component

The only property for the connector is the connection information for mqtt.Client#connect

Example Root component:

import { Connector } from 'mqtt-react';
import App from './components/App';

export default () => (
  <Connector mqttProps="ws://test.mosca.io/">
    <App />
  </Connector>
);

Subscribe

Example Subscribed component:

import { subscribe } from 'mqtt-react';

// Messages are passed on the "data" prop
const MessageList = (props) => (
  <ul>
    {props.data.map( message => <li>{message}</li> )}
  </ul>
);

// simple subscription to messages on the "@test/demo" topic
export default subscribe({
  topic: '@demo/test'
})(MessageList)

Example Posting Messages

MQTT Client is passed on to subscribed component and can be used to publish messages via mqtt.Client#publish

import React from 'react';
import { subscribe } from 'mqtt-react';

export class PostMessage extends React.Component {
    
  sendMessage(e) {
      e.preventDefault();
      //MQTT client is passed on
      const { mqtt } = this.props;
      mqtt.publish('@demo/test', 'My Message');
  }  
  
  render() {
    return (
      <button onClick={this.sendMessage.bind(this)}>
        Send Message
      </button>
    );
  }
}

export default subscribe({
  topic: '@demo/test'
})(PostMessage)

Advanced Susbcription / Integration with Redux:

It is possible to provide a function that handles received messages. By default the function adds the message to the data prop, but it can be used to dispatch actions to a redux store.

import { subscribe } from 'mqtt-react';
import store from './store';


const customDispatch = function(topic, message, packet) {
    store.dispatch(topic, message);
}


export default subscribe({
  topic: '@demo/test',
  dispatch: customDispatch
})

Credits

Sponsored by nearForm

Contributing

Pull Requests are very welcome!

If you find any issues, please report them via Github Issues!

Contributors

License

(MIT)

0.0.11

5 years ago

0.0.10

5 years ago

0.0.9

5 years ago

0.0.8

5 years ago

0.0.7

5 years ago