Skip to content

This is a simple example of how to use MQTT.js library in a React Native project.

License

Notifications You must be signed in to change notification settings

MaximoLiberata/react-native-mqtt.js-example

Repository files navigation

MQTT.js implementation example for React Native

This is a simple example of how to use MQTT.js in a React Native project. This example also is using Expo to make it easier to run the project.

Table of Contents

Getting Started

  1. Clone this repository
  2. Install the dependencies with npm install
  3. Copy the .env.example file to .env and configure the MQTT broker settings
  4. Run the project with npm start
  5. Open the project in your device using the Expo Go APP reading the QR code that will appear in the terminal.
  6. Publish a message from your MQTT Broker

Environment Variables

Variable Type Description Example
EXPO_PUBLIC_TZ string Timezone will be used to format the date UTC | America/Santo_Domingo
EXPO_PUBLIC_MQTT_HOST string MQTT Broker Host localhost | domain.com
EXPO_PUBLIC_MQTT_PORT number MQTT Broker Port 1883
EXPO_PUBLIC_MQTT_PORT_SSL number MQTT Broker SSL Port 8883
EXPO_PUBLIC_MQTT_SSL boolean Enable connection via SSL true | false
EXPO_PUBLIC_MQTT_VERSION number MQTT Protocol Version 3 = 3.1
4 = 3.1.1
5 = 5
EXPO_PUBLIC_MQTT_QOS number MQTT Broker Quality of Service 0 | 1 | 2
EXPO_PUBLIC_MQTT_USERNAME string MQTT Broker Username producer | consumer
EXPO_PUBLIC_MQTT_PASSWORD string MQTT Broker Password 123 | 456
EXPO_PUBLIC_MQTT_TOPICS string MQTT Broker Topics separated by comma , topic/1 | topic/1,topic/2 | topic/#

Config MQTT.js in React Native

React Native (RN) doesn't support some technologies as web browsers does, in RN the mqtt client always will be established from a WebSocket instance, for that reason you need some extra packages to make it work. Here is a list of the packages that you need to install to make it work:

About important files

File Description
/App.js Main entry point of the application
/src/screen/Mttq.jsx The screen that will show the MQTT logs

Motivation

I was looking for a simple example of how to use MQTT.js in a React Native project, but I couldn't find any. So I decided to create this example to help others that are looking for the same thing. In the process I found a issue with the mqtt package that I had to fix, the PR is in (#1840) if you want to check it out.

Contributing

Feel free to make a PR if you find any issue or if you want to improve this example. Also, if you have any other issue with the mqtt package, feel free to open an issue in the MQTT.js repository.

Contributors

About

This is a simple example of how to use MQTT.js library in a React Native project.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published