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…

How to implement Internationalization for a React Application

Internationalization of an application, document or product refers to the development of easy content localization, i.e. modifying the content to target the language and culture of the region. Internationalizing an application leads to improved usability by people located across the globe.

There are two main aspects to internationalization, firstly the detection of the user’s local language, and secondly the modification of the content, including translation of the text, and switching relevant items such as currency.

This article addresses how to implement the internationalization of a React application using the library ‘React-intl’. The first step is to create a new React project and add the intl package:

  • Create a React project using the commands –

$ npx create-react-app project_i18n

         $ cd project_i18n

  • Add the ‘react-intl’ package.

Configuration of the package consists of four main steps: creating the locales, creating the provider, and finally creating a common translator. In the remainder of this article, I will elaborate on these steps.

1. Create the locales –

a.Create a folder with the name ‘i18n’ in your code folder.

i18n folder 2

b.Create a file ‘locale.js’ and export the locales object.

locale js3

2. Create the provider –

a.Now, let’s create the Provider to hook the IntlProvider to the application.
INTLprovider4
In the above image, IntlProvider is imported from react-intl and a wrapper is created for the application, setting the default locale and passing the message content according to the locale.

b.To create the messages for the respective languages, create a folder called ‘MessageContent’ and create the locale files for messages within that folder.
Let us create two different message objects.
For English: – en-US.js –

EN-US5

For French:- fr-CA.js –

FR-CA 6

c. Create an ‘js’ file under the MessageContent folder to export the messages.
MessageContent-> index.js –

Messagecontent 7

3. Create a common translator –

a.Let us create a common Translate function to translate the message according to the locale.
i18n-> translate.js –

Commontranslator8

b.Create ‘index.js’ under the ‘i18n’ folder to export the locales and provider as default.
i18n-> index.js –

index.js9

c.Finally, let us wrap the application with IntlProvider and set the locale in App.js.
src-> App.js –

wrappingapp10

Example for French Locale –

fr-CA.js

export default {

[LOCALES.FRENCH]: { ‘hello’: ‘Bonjour’, ‘userName’: ‘le nom d\’ utilisateur est {uname}’

}

};

translate.js

const translate = (id, value={}) => <FormattedMessage id={id} values={{…value}}/>

d. We are looking for the following output:

translate(‘hello’)  => Bonjour

translate(‘userName’, {‘uname’: ‘Sam’}) => le nom d’ utilisateur est Sam

Bonjour11

Internationalization can be achieved in react application by using ‘React-intl’ with minimal development efforts for handling multiple languages.

MetaSys has developed custom React solutions for clients across various industries and geographies. If you have any questions on internationalization in your React projects, then please feel free to contact us. 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.

Our experience of using React Hooks and what you can learn from it!

React JS is now a very popular programming language. React Hooks has unlocked new capabilities and allows you to create great applications. It allows one to write very compact code. We share our experience of how we have used React Hooks. We assume here that you have some React Programming knowledge.

React Hooks are functions that allow you to hook into React lifecycle and state features. They primarily serve as an alternative for classes. They can help in keeping your components clean and perform better. Hooks are a recent  addition in React version 16.8.0.

In this article, we are going to show you how to convert a React class into a functional component using the useState Hook.

Hooks don’t work inside classes because they let you use React without classes. We will use the built-in hooks instead of React lifecycle methods. Eg. useState, useEffect, useRef etc.

We are covering useState, useEffect, useRef React hooks in this article. useState() is used to replace the constructor functions and state declarations. While useEffect() is used to replace componentDidMount() and componentDidUpdate(). You can use useEffect as many times as you need to in single component. And the last one, useRef has another cool usage besides DOM refs, it is also a generic container whose current property is mutable, it also can hold any value similar to an instance property of a class.

Steps to convert a React class component into a functional component using React Hooks –

React Hooks

Step 1. Change ‘class ComponentName extends Component’ With ‘function ComponentName(props)‘

Step 2. Remove “this.” And “this.state” from the entire component.

Step 3. import React, { useState } from ‘react’

Step 4. Remove the constructor. Add its logic as shown above in the image for initializing the state variables with the help of useState hook.

Let’s understand conversion into useState, useEffect and useRef with examples –

  • useState() Hook –

The parameter of the useState hook is the initial value of the state. This hook provides the array with two values – the first is the name of the state and the second is the function name which updates the value of that state.

Eg.

const [num, setNum] = useState(0); //declaration

setNum(10) //use

Here num is the state name, setCount is the function that you can use anywhere in the component to update that state.

Here are some examples of setting or initializing state variables for different data types –

//Set an Integer

const [num, setNum] = useState(0);

setNum(10);

 

//Set a String

const [name, setUsername] = useState(‘John’);

setUsername(‘Smith’);

 

//Set a Boolean

const [isValid, setIsValid] = useState(false);

setIsValid(true);

 

//Set and Array

const [items, setItems] = useState([]);

setItems([0,1,2,3,4]);

setItems([{id:0, color:”red”},{id:1, color:”green”},{id:2, color:”blue”}]);

 

//Set and Object

const [form, setValues] = useState({

id: 0,

firstName: ‘’,

lastName: ‘’,

subscribe: false

})

 

setValues({

…form,

firstName: ‘Jamie’,

subscribe: true

})

 

 

  • Replace lifecycle methods (compentDidMount, componentWillUnmount,

 componentWillReceiveProps, componentDidUpdate) with useEffect

 

e.g.

const [items, setItems] = useState([]);

const [num, setNum] = useState(0);

 

  1. compentDidMount

 

useEffect(()=>{

setItems(items);

}, [])   // Here empty array indicates don’t look for any updates

 

b.componentWillUnmount

 

useEffect(()=>{

return () => {console.log(‘unmounting the component’)}

},[])

 

c. componentDidUpdate/componentWillReceiveProps

This will get executed when your ‘num’ state variable and ‘id’ props will get updated.

 

useEffect(()=>{

if (!isEmpty(num))

{

console.log(‘num changed = ’,num);

setItems(items);

}

 

if(!isEmpty(props.id))

{

console.log(‘props.id changed = ’,props.id);

}

},[num, props.id])

 

 

  • Use of useRef

 

const [num, setNum] = useState(0);

const prevNumRef = useRef();

useEffect(()=>{

prevNumRef.current = num;

})

const prevNum = prevNumRef.current;

return <h1>Current value : {num}, previous value = {prevNum}</h1>

 

Advantages

1.With React hooks, the component will be cleaner and easier to read (fewer lines of code). Hooks are easier to work with and to test.

2.It is easy to make code reusable. They don’t create another element in DOM like HOCs in React do.

3. useState – it allows to update different states with specific functions. The ability to move the state update logic as a separate hook.

 

Disadvantages

1.useEffect hook allows to merge three lifecycle methods such as componentDidMount, componentWillUnmount and componentDidUpdate into one and the issue with useEffect is the second parameters ,i.e. the array that we need to pass to define this behaviour. It is not explicit enough.

2.React Hooks are new additions to React. So to convert and test a complex class can be a time-consuming task initially .

3.Since it is relatively a new addition it may not be compatible with all third party libraries. But this is rapidly changing .

This is all about React Hooks in a nutshell. If you are looking to build any a mobile or web application using React technology, then please contact us.

Happy coding!

React Native vs Native apps development

React Native has some exciting features that make it popular in the developer community. Many popular apps such as Instagram, Facebook Ads Manager, Walmart, SoundCloud and Netflix are based on React Native. We have worked with both Native app development and React Native, and in this article we share our experience and give some examples. First, a few words regarding the advantages and disadvantages of each.

Native App

A Native application is a software programme developed for a particular operating system. This application can be developed using Java or Kotlin for Android and Objective-C or Swift for iOS and C# for Windows.

  1. High performance – Native apps run much faster than hybrid apps because they are fully supported by the OS on the device.
  2. Better UX/UI – User experience is much better because the higher performance allows everything to run smoothly. Depending on the business need, you can develop device-specific features directly within a Native app.
  3.  Interactive – Native mobile apps run more smoothly in comparison to hybrid apps. The interaction with the user is intuitive and natural as they have specific UI standards for each platform.

The major disadvantage of Native apps, is that they work only for one OS, leading to extra development time, and cost in building apps for multiple platforms.

React Native

React Native is an open-source JavaScript framework for building iOS and Android apps. It is famous for its lightweight framework for mobile app development.

  1. Faster development across multiple platforms – React Native allows sharing of the entire codebase between operating systems (Android and iOS). Once you develop an application for Android, you can compile it on iOS and vice versa. This results in a  significant saving in the development effort as compared to developing natively on both Android and iOS platforms.
  2. It gives a Native app feel – With React Native, most of the features can be developed as a Native feature. This means that the user experience is the same as a Native app, despite the fact that hybrid technology has been used.
  3. Large Community of Developers – React Native is a popular open-source JavaScript framework, with a well developed community. This means that queries are generally answered quickly on websites such as StackOverflow and GitHub. Furthermore, many helpful libraries created by other developers are freely available for download.
  4. Easy and Live Reloading – When using React Native, code changes are immediately reflected on the simulator and can be tested instantly. By eliminating the need to recompile after every change, a lot of development time is saved.
  5. Cost reduction and Code reuse – With React Native technology, more than 80% of the code can be reused between the Android and iOS platforms, saving a huge amount of development time and cost.

We found that React Native is a superior method that results in major time saving for mobile app development for multiple platforms. Two examples from our experience with React Native are:

  1. App with SQLLite for multiple platforms
  2. App with Bluetooth connectivity feature for multiple platforms

The reason we opted for React Native for these apps, is that in both cases the same business logic layer was required to create two Native apps. Our team successfully built a common business logic layer and UI for both the platforms. We saved significant time and cost due to the reusability of the code. Future maintenance will also be cost-effective. Furthermore, we found that Bluetooth and SQLLite features work efficiently in React Native even though they are not Native based.

MetaSys Software has developed custom solutions for clients who are in different sectors using React technology. For more info https://www.metasyssoftware.com/react

TypeScript in React

TypeScript is a useful technology for maintaining code quality and for self documentation of code in React. The use of “self-explanatory” code significantly reduces development cost and time. Typescript reduces the code analysis time and aids quick understanding of the existing implementation. This article serves as an overview for budding developers who wish to learn more about TypeScript.

Now, let’s understand – what is TypeScript?

TypeScript is an open-source programming language maintained and developed by Microsoft since 2012. It is a set of tools which uses a strongly typed, object-oriented and compiled language. It is an extended JavaScript programming language with additional features. When a new developer joins the team and uses any existing component of the project, he can easily understand its props with their specific types.

According to GitHub, TypeScript is one of the fastest-growing technologies. It is downloaded 31 Million times per month. Developer survey results of 2019 on stack overflow, place TypeScript at 10th position for “Most popular technology” and 3rd position for “Most Loved technology”. So as a new developer, it is not something which you can ignore.

When to use TypeScript?

Development teams working together on coding projects can struggle with code complexity, particularly as projects increase in size. TypeScript is recommended for large projects as it is the best option for maintaining code quality. It enables self-explanatory code right from the initial stages of the project.

Some of the significant features of TypeScript are listed below:

1. Static typing –
The static typing feature is one of the common reasons for developers to migrate their existing project from JavaScript to TypeScript. You can add data-types for variables, functions, properties, interfaces, etc, and it indicates warnings and errors regarding data type issues even before the compilation. I think that’s a wonderful feature because as a young developer, I faced a lot of problems while doing scripting.

static typing

static typing 2

Note: Static typing is optional.

2. Object-oriented –
TypeScript supports object-oriented programming, i.e. you can use class, Inheritance, Encapsulation, and Polymorphism.

3. Code suggestion –
It is best to use TypeScript with the IDEs since IDEs provide features such as IntelliSense and error highlighting.
If a developer wants to access the component props {this.props.}, then Typescript suggests all the available props, and highlights any typos.

Code suggestion

4. Display errors/warnings ASAP –
TypeScript highlights the errors immediately.

display error image 1

display error 2

5. TypeScript is portable –
All companies have a different kind of IT infrastructure set-up, with different operating systems and browsers. The advantage of TypeScript is that it is a superset of Javascript, meaning it can run on any environment that Javascript runs on. It is portable across operating systems and browsers.

How to create a new React JS project enabled by Typescript? –
To create a new project which is enabled by Typescript, you can use the following command.
e.g. npx create-react-app <> –TypeScript

It creates tsconfig.json which has typescript configurations.
tsconfig.json
{
“compilerOptions”: {
“target”: “es5”,
“lib”: [
“dom”,
“dom.iterable”,
“esnext”
],
“allowJs”: true,
“skipLibCheck”: true,
“esModuleInterop”: true,
“allowSyntheticDefaultImports”: true,
“strict”: true,
“forceConsistentCasingInFileNames”: true,
“module”: “esnext”,
“moduleResolution”: “node”,
“resolveJsonModule”: true,
“isolatedModules”: true,
“noEmit”: true,
“jsx”: “react”
},
“include”: [
“src”
]
}

Here, you can find the set of rules defined for the project. You can also modify or add more constraints if you want.

How to add TypeScript to the existing React JS project?
To add TypeScript in the existing project, you will have to install TypeScript and other required types externally
e.g. npm install –save TypeScript @types/node @types/react @types/jest @types/react-dom

After this, two changes are needed in the projects:
– First, rename all the “.js” file to “.ts” or “.tsx”
– Secondly, create a tsconfig.json in the root directory with the set of rules mentioned in the first step.

Happy Coding!!