Usage of MQTT protocol in React

gil picture gil · Feb 23, 2018 · Viewed 10.1k times · Source

I'm kinda new to react and trying to understand how to make MQTT work with it.

i've tried to follow the code sample published here: https://www.npmjs.com/package/mqtt-react

but had no success. for some reason it's just don't do anything.

here's my code:

App.js class:

import React, { Component } from 'react';
import './App.css';
import PostMqtt from './PostMessage.js';
import {Connector} from "mqtt-react";

class App extends Component {
    render() {
        return (
            <div className="App">
                <PostMqtt/>
            </div>
        );
    }
}

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

PostMessage.js class:

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('sensor', 'My Message');
    }

    render() {
        return (
            <button onClick={this.sendMessage.bind(this)}>
                Send Message
            </button>
        );
    }
}

export default subscribe({
    topic: 'sensor'
})(PostMessage)

Any ideas what goes wrong? thanks!

Answer

gil picture gil · Mar 1, 2018

after long research i've found out the solution.

the connector above supports MQTT over web sockets. the default mosquitto MQTT port is 1883 which goes directly to MQTT broker and not via websockets, and that's why it didn't connect.

the solution is to use port 8080 which is "MQTT over WebSockets, unencrypted" (according to the mosquitto documentation).

so all i had to do is change the following row from to and it worked.

hope it helped someone.