Effective use of Context in a React Application

The prerequisite to comprehend this article is a fair knowledge of Hooks. Hooks is a new addition in React 16.8 that let you use state and other React features without writing a class.

In a React application, we can pass data from parent component to child components using the prop. However, this is limited to certain type of properties such as Theme, locale preference, etc., which need to be used at global level in the application. With React Context, we can use the data or props without explicitly passing them as props to the component.

Context has three main elements. We need to understand these elements to utilize Context to the fullest.

  1. Context ObjectThe Context object is designed to share data globally in the application.
  2. Context ProviderThe Context object comes with a provider that can be used to consume Context data in the React component.
  3. Context Consumer The Context Consumer is wrapped inside the Context provider, and it is used to get access to the Context data.

In this article, let us see how to create a Theme Context using typescript step by step.

1.Create Theme Context Object. Export ThemeContext and set the Context default value to ‘undefined’.

Theme context object

2.Create the Theme object by using two Themes, for instance, here we are going to use ‘dark’ and ‘light’.

Create Theme Object

3.Create Theme Context provider.

Theme Context Provider

4.We created the Theme Context Provider by setting the Default Theme and function to change the Theme.

5.Subscribe Theme Context by wrapping the component with Context provider.

SubscribeThemeContext

6.Use or set the Context data as shown in the screenshot below.

Context data React

The concept of Context is simple yet effective. In this article, we covered how to use Context in the React Application with Theme Context example using TypeScript.

Should you have any queries, please contact MetaSys Software React experts, who have abundant experience in engineering applications using latest dev-tools such as React-Redux, React Hooks, React Router, React Bootstrap, etc.

You can reach out to us with any coding queries too! We would be happy to help!

Happy Coding!

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!