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 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!

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!

Six smart steps to configure Mapbox with ReactJS

Mapbox provides custom maps, search and navigation. It supports many platforms. The tool is powered by programmers as well as millions of devices providing Location Data. It provides developers a platform and a toolset to build customized applications where location-based data can be used to meet a variety of business requirements.
A typical scenario where Mapbox is used:
A service provider uses Mapbox to track locations of their assets or employees in order to provide real-time information to customers or for operational monitoring. This could be a restaurant delivery service, an international transport company or even a fleet operator in a city.
Customizing Mapbox
One of our clients provides data services to monitor the health of agricultural farms. They wished to offer compelling data visualization of agricultural farm images along with other details. We customized mapbox to render this information on the web and mobile devices. There are SDKs available for the Web, iOS and Android.
In this article, we share how we configured mapbox in React JS using custom style to add new fonts, custom icons and publish these styles.Following are the steps involved –
1. Steps to generate the token number and style in Mapbox

  • a. Create an account on https://account.mapbox.com
  • b. Log in to your account
  • c. On the Dashboard look for the Default public token. This Token number can be used for configuration in the Web App. You need to remember that this token number is public and easily accessible from the developer tab.
  • d. To get the private Token click on the button ‘Create a Token’ you will get a form. Enter the ‘Token name’ and select the desired ‘Public Scope’ and the ‘Secret Scopes’.
    Access tokens
  • e. Note: – This token will only be accessible from the specific URLs that we add while generating the Token.
    Create an access tokenToken Restrictions
  • f. Now add the list of comma-separated URLs into the URL field and click on the ‘Create Token’. Next you will be asked to confirm with your account password.
  • g. You will find the private token at the bottom of the Token list.
    Private token

2. Steps to configure React JS app with Mapbox

  • a. There are two different methods available for using the Mapbox on the web App.
    We describe the steps using the ‘npm’ module bundler for installing Mapbox GL JS.
    Method selection for installing Mapbox
  • b. Install the ‘npm’ package –> ‘npm install mapbox-gl –save’
  • c. Include the GL JS CSS file
  • d. Include the CSS file in theof your HTML file
    • i.<link href=’https://api.mapbox.com/mapbox-gl-js/v1.3.1/mapbox-gl.css’ rel=’stylesheet’ />
  • e. Add the map to your Web App.
    • i. var mapboxgl = require(‘mapbox-gl/dist/mapbox-gl.js’);
    • ii. mapboxgl.accessToken = ‘Your Token number’;
    • iii. var map = new mapboxgl.Map({
    • iv. container: ‘YOUR_CONTAINER_ELEMENT_ID’,
    • v. style: ‘mapbox://styles/mapbox/streets-v11’ // Default style link
    • vi. });
  • f.  Now you are done with the configuration.

3. Steps to create the custom style of Mapbox

  • a.To create our custom style for the map, we need to open the Mapbox Studio,
  • b.To open the Mapbox studio, you can to go to the Dashboard and then click on the ‘Design in Mapbox Studio’ on the right side of the Dashboard or Just click on the link here https://studio.mapbox.com/
  • c.After opening the Mapbox studio, you can see the predefined styles you can use directly or you may choose to create a new style.Mapbox styles
  • d. To create a new style, click on the ‘New style’ button on top of the page.
  • e. Select the desired template from the list and can change the style of the map from bottom of the dialog and then click on the customize button.Templates
  • f. You can see a dashboard with different settings.
  • g. You can update the style of the country label, background, road, buildings and many moreUpdating styleicons

4. Steps to add a new font to the map and then publish for production

  • a. Click on the Fonts tab on the top-right corner then you can find a dialog to upload the new fonts.Upload fonts
  • b. Clicking on the Upload new font, you can see a new dialog with the title ‘Upload fonts’ here you can drag new fonts with extension ‘.TTF’ and ‘.OTF’.
    Upload new font
  • c. Once Font family is added, it can be then used in the map.
    icons

5. Steps to add a custom icon or an image and publish

  • a. The image we upload here will be available as an icon on the map for example Image as a custom marker.
  • b. Click on the ‘Images’ tab in the header you can see a dialog to upload the SVG image.
    Upload svgDrag and drop svg images
  • c. To upload the SVG image, click on the ‘Upload SVG Icon’ button, now you can see a new dialog where you can drag your SVG image.
  • d. Once you update any style, you have to publish the style to see the changes on the map.
  • e. Note: – It may take some time to get published and to reflect on the map.
  • f. It is very easy to publish the changes; you just have to click on the ‘Publish’ button on the top-right corner of the map box studio.
    Image
  • g. Now you can see a dialog with a slider where you can see the styles you added.
  • h. Here you can either ‘Publish as new’ which will replace all the styles, or, use the ‘Publish’ button to add the styles you added in your draft.
    Basic template

6. Steps to add the updated style to our map

  • a. Once the style is published,click on the ‘Share’ tab on the top-right corner of the Mapbox Studio. Here you can see a dialog where you can find your ‘Your style Url’ and ‘Your access token’.
    Share
  • b. Now update your style URL of the map.
    • i. var map = new mapboxgl.Map({
    • ii. style: ‘Add your style URL Here’
    • iii. });
  • c. Example:
    • i. const feature: feature = {
    • ii. id: 123,
    • iii. type: ‘Feature’,
    • iv. geometry: feature.geometry,
    • v. properties: {
      • 1. meta: feature.meta,
      • 2. icon: ‘square-stroke’
      • 3. // Custom Icon name which is added to the style in Mapbox Studio
    • vi. }
    • vii. }

We at MetaSys software have helped the clients in building such kind of custom software solutions. For more details – https://www.metasyssoftware.com/case-study-react