How to Create a React Native NPM Package?

NPM is a Package Manager for Node JS. It was first created in 2009 as an open-source project to help JavaScript developers to easily share their code in the form of packages. NPM allows you to install the various public packages for the project. NPM has over 8,00,000 packages with public access.

My intention behind writing this blog is to help React-native developers create their own package. If any developer wants to share his own package on the NPM registry, then he needs to make it public. This allows developers to contribute to the NPM ecosystem. Steps to create and publish a react-native NPM package are as follows:

There are 3 phases to create and publish a package.

1. Creating the NPM package.
2. Testing the NPM package on the react-native app.
3. Publishing on the NPM website.

1. Creating the NPM package:

First create a folder where package information like package.json, .babelrc, webpack.config.js, etc will be stored. We will introduce these files soon.

Now navigate into that folder directory using terminal and run command – npm init

You will be prompted for the package name, version, main, keyword, etc. You can skip questions (by pressing enter) (it is easy to modify later). At this point, a package.json file will be created.

Now, open the package.json file in your IDE (code editor) and install all the dependencies as below using – npm install dependency-name.

Below is an example of package.json file.

Package JSON

Note: “main” should be the same as above.

Now create a file .babelrc and add the following lines. Babel is a compiler to convert JavaScript code into ES5 JavaScript.

React Native image

Let’s create a file named webpack.config.js and add the lines below.
Remember, webpack is the builder. It compresses code into ‘build’ that can be deployed in the React-Native app. Make sure “entry” is either ./src/index.js or ./index.js depending upon your file structure.

webpack

Now, create a folder src, add the index.js file and add your component.

src image

Whenever you make any change to your package, you have to create the build again using command – npm run build. After that, you must re-install it in the react-native app.

Once you configure the above steps, your folder structure should look as follows

React test library

2. Testing the package on React-Native app:

To test or use your package, you will need a React-Native app. Create a React-Native app by executing the run command npm create-react-app “your app name” and open it in your IDE.

You can install your package in two ways

1. Upload it on the NPM website and then install it using npm i “package name”.
2. Locally install it through a relative path of NPM package to react-native app npm i ../react-test-library

React Native

Note: We will try to avoid the first option because whenever there is any change in your NPM package, you have to re-publish it on the NPM website and re-install it on your project.

So we will test it locally first and then upload it on the NPM website.

To check your package, you have to install it through the relative path as shown in the above example and import your component from your package.

src/App.js

src

To see the result of the installed package, run the command in your react-native app – npm start.

npm package

Now, let’s see the final step.

3. Publishing on the NPM website:

For publishing any package, you should have an account on the NPM website (if not you can create one). While uploading the same package, the package version should be unique each time.

Steps to upload your package –

1. Using the terminal, navigate to your package directory.
2. Run command – npm login. Enter a username, password, and email id.
3. Run command – npm publish.

Once your package has been published, you can check it on the NPM website.

React test library

At last, you are able to create your own library. In case of any queries feel free to share your feedback in the comments section below.

Happy Coding…

Flutter vs React Native

Many new technologies have evolved because of the increasing demand for cross-platform products. Facebook’s React Native and Google’s Flutter have created a lot of buzz in the cross-platform app development market. These two trending technologies are both known for high performance, and many enterprises and big brands are embracing them to come out with value-driven web and mobile applications.

React Native and Flutter are currently competing with each other to become the leading product, and although both have their advantages, it is not yet clear which one will come out on top. This article compares the technologies by examining their features, and their respective advantages and disadvantages. We hope this can help you in choosing which technology to use for your application.

Before looking at the technical differences, let us briefly have a look at their positions in the market so far. In order to do this, we can use Google trends to look at the interest in the technologies since 2015, when React Native was launched.

Google Trends comparison 1

The trend shows that both technologies have been gaining popularity steadily, and that although React Native is much older, Flutter is catching up quickly.

About Flutter

  • Flutter is a free, open-source portable UI toolkit for creating web, desktop, and natively compiled mobile apps in a single codebase.
  • It was created by Google in 2017.
  • It uses a language named Dart.

 About React Native

  • React Native is also a free, open-source mobile application framework.
  • It enables the developers to use its parent framework React with the native platform.
  • React was created by Facebook in March 2015.
  • React Native is virtually identical to React.

Head to head comparison between Flutter and React Native

Flutter vs React Native comparison

Let’s list a few of the major advantages and disadvantages of each technology.

Flutter

Advantages:

  • Fast apps
  • User-friendly design
  • Perfect for MVC structure

Disadvantages:

  • Large Apps can be difficult to program
  • Limited libraries in comparison with React Native
  • Currently small developer community (though growing)

React Native

Advantages:

  • Active large community
  • Uses widely popular JavaScript language
  • Robust Performance
  • Easy to learn

Disadvantages:

  • Lots of abandoned libraries and packages
  • App size is bigger than Natively developed Apps
  • Fewer testing features compared to Flutter

Which technology should we choose in 2020?

React Native has a huge base of achievements to showcase its success in the market, compared to the new player. However, Flutter has a lot of potential and as of now there is a chance that it can become the leading technology for cross platform mobile app development and web applications. We hope that this article has highlighted some of the key differences and can help you choose the best technology for your app development.

Happy Coding…

React Redux – The art of state management

React is one of the most popular technologies for front-end development, which uses a component based approach to enable fast app development. Redux is a predictable state container for JS apps, and works particularly well with React.  In this article, I will be covering some basics on how to set up React-Redux for state management of a UI.

To illustrate the advantages of this approach, have a look at the UI structure shown below.

UI structure image 1

Let’s say the functionality required is that when a user interacts with the big component, the application has to update the small component and the header. In other words, we need to sync the header and small component as well as manage the states of all the other components. Without a state management library such as the one provided by Redux, coding this implementation can easily become very complicated.

Using the state functionality in React allows only the use of local, component level states.

Image 2

You can store the states using setState method, and fetch the stored state using state.[STATE_NAME]. However, these states are local, and only available within the class component in which it is declared.

Setstate image3

To store the states at the application level, i.e. the global level, in order to access them from different components, we can use React-Redux.

Let’s see how React-Redux works

You will see three main elements in the Redux architecture – Store, Dispatch Actions and Reducers.

Redux architecture 4

Store: holds the states at the application level, and allows any component to get data from the store in the form of Redux States.

Dispatch Action: a function of the Redux Store to trigger a state change.

Reducers: It handles the value change in Redux State.

How to configure React Redux in a React JS project –

The following packages are needed to be installed to configure  Redux in the project –

  1. Redux: the core package of React Redux.
  2. React-redux: needed for React bindings.
  3. Redux-thunk: a middleware which allows you to call action creators, and which returns a function instead of the action object.

These dependencies can be installed by using the following NPM command –
npm install redux react-redux redux-thunk –save

After these dependencies are installed, a store can be created and initialized with data/null values as per the requirements. This can be done by creating the file store.js in the project.

First however, you need to create reducer.js to handle the next states. Below is the example of reducer.js to initialize the state. Here, it is just returning the initial value from the reducer.

reducer.js 5

Below is a slightly more complex example of the code in reducer.js to update the states based on the action executed from the component.

coding 6

In the above example, it adds the data to the state upon the dispatch action (ADD_DATA). Now let’s create the action to dispatch. You can create a file with the name action.js, that contains the code shown below.

action.js 7

Once the action is created, now you can create a store and then connect the store to the application. You can create a file with the name store.js, that contains the code shown below.

store.js 8

To connect the store to the application, you will have to use the entry point. In the index.js (i.e. entry point of the app), import the store as shown below –

coding 9

These are all the Redux configurations for an application. Refer the the image below to use it in your component –

React component 10

React Redux can handle large amounts of data at the application level with cleaner components and is particularly useful for big applications.

Without Redux 11

With Redux 12

Without redux, to transfer data from component 1 to component 5, you need to pass it through middle components. This increases the props for components and creates more complexity and the components are less clean.

Using React-Redux, you can get or set the data to the store from any of the components directly by mapping the redux states to component props. In this case, you do not need to pass props to the middle components. This allows for much cleaner components and increased clarity in the code.

If you are looking to build a mobile or web application using React technology, then please feel free to contact us.

Bluetooth Low Energy (BLE) technology usage and its communication with mobile devices

BLE is a wireless technology for a personal area network that is designed and marketed by the Bluetooth Special Interest Group. It is a low power-consuming device which maintains the same communication range as that of Bluetooth classic. It is mainly used in small and low power consumption devices such as a, smartwatch, BLE keychain, true wireless Bluetooth earphones, etc.  It is compatible with most of the mobile phones, tablets, and computers.

In this article, we will share how a BLE device works and how it communicates with Android and iOS devices for transferring and receiving information/data. But prior to that, let’s try to understand where BLE technology is used.
BLE

  1. 1. Device Tracking: BLE device is a tiny device that can transmit the data. It consumes very low power and can be used to track the assets and people within a range of 30 meters.
  2. 2. Machinery Diagnosis using BLE: Machine Diagnostics is possible through BLE. BLE can be integrated into the machines and used to transfer data. All key statistics as well as detailed diagnosis-related data can be retrieved from machines and transmitted to mobile devices/computers for detailed analysis.
  3. 3. BLE Proximity real-time location: BLE devices are capable of broadcasting radio signals at regular intervals. These signals can be captured by any mobile device (Android, iOS or any other compatible devices). The mobile application can then establish or pinpoint the BLE location.
  4. 4. Better retail experience: Marketers can enhance the shopping experience by attaching BLE enabled tags to products. When customers are in the vicinity of the store, they would get the latest offers/coupons/discounts for these products on their mobile app.
  5. 5. Locating people: BLE technology can be effectively used in events where you need to coordinate with different people within a particular facility.
  6. 6. Home Automation Systems: BLE is used in Home Automation Systems because of its low power consumption and low cost.
  7. 7. Health monitoring system: BLE is the best choice for health monitoring systems like fitness bands. It collects information from the human and animal body and transfers data to the mobile device using a Bluetooth connection. Since it has a low power consumption feature, it can be easily integrated with small handheld devices for better battery usage.

There are different steps involved for searching BLE peripherals, establishing the connection, writing and reading characteristics. They are as follows:

  • 1. Scan nearby BLE peripherals: To get all available nearby BLE peripheral.
    manager.startScan( ).then(availableBLEPeripherals =>{
    console.log( availableBLEPeripherals );
    }).catch(error => {
    handleError( error );
    })

 

  1. 2. Connection and Disconnection:
      1. a. To connect the BLE peripheral:
        manager.connectBle( peripheral ).then( peripheral => {
        console.log( “Connected peripheral :-”, peripheral );
        }).catch( error => {
        handleError( error );
        })

     

      1. b. To disconnect the BLE peripheral:
        manager.disconnectBle( peripheral )then( peripheral => {
        console.log( “Disconnected peripheral :-”, peripheral );
        }).catch( error => {
        handleError( error );
        })

     

  2. 3. Start listening for incoming data:
      1. a. To get all the incoming data from BLE:
        manager.monitorBle( peripheral.id, peripheral.characteristics).then( ( response ) => {
        console.log( response );
        }).catch( error => {
        handleError( error );
        })

     

  3. 4. Write characteristic:
      1. a. To fire query to BLE peripheral:
        manager.writeData( peripheral.id, peripheral.service, peripheral.characteristics, dataToSend ).then( response => {
        console.log( response );
        }).catch(error => {
        handleError( error );
        })

     

MetaSys Software has developed custom mobile solutions for clients who are in different sectors using React Native technology. For more information on our React Native app development projects – https://www.metasyssoftware.com/react