Tuesday, August 21, 2018

componentDidCatch example

The componentDidCatch life-cycle method is invoked when an exception is thrown in its child component hierarchy. Components which implement componentDidCatch are called Error Boundary components. These components act as catch {} blocks to capture exceptions.

The following example has 3 components
ErrorBoundaryComponent - Implements componentDidCatch, acts as a catch {} block to capture errors in child components.
ChildComponent - Actual UI component, encapsulated in ErrorBoundaryComponent
RootComponent - This is the bootstrap component which launches the application.

React Component Lifecycle - componentDidCatch

The componentDidCatch life-cycle method is used to create special Error Boundary components. Prior to react v16.0 there was not structured way of error handling, if a component throws an exception then the application will crash and we might have to refresh the page.

To overcome this React v16.0 introduces error boundaries. Error boundaries are special components which catch errors in its child component hierarchy and display a custom error / fallback UI. Error boundaries handle any errors in the render(), constructor or any of the component life cycle methods in its child component hierarchy.

Friday, August 17, 2018

React Component Lifecycle - componentWillUnmount

The componentWillUnmount life-cycle method will be called when a component is being removed from DOM. This method can be used to perform any required cleanup operation like cancelling pending network requests, cancelling subscriptions etc.

This is the only life-cycle method invoked in the component un-mounting phase.

Below is the syntax for componentWillUnmount

componentWillUnmount() {
  // perform cleanup operation here.
}

Thursday, August 16, 2018

React Component Lifecycle - componentDidUpdate

The componentDidUpdate life-cycle method is the last life-cycle method invoked in the update phase. This method will be invoked after render() and can be used to operate on DOM after the component is updated. Similar to componentDidMount this method can be used to make Ajax/Api calls. Note that any change in the state/props due to the Ajax calls will re-trigger render(). We should make sure that any change to the state in this method is wrapped with proper conditions so as to avoid infinite loops.

Wednesday, August 15, 2018

shouldComponentUpdate example

The shouldComponentUpdate life-cycle method is invoked in the update phase before the render(). This method will be invoked when the component receives new state or props, this method can be used to prevent re-rendering of the component. If shouldComponentUpdate returns false then render() will not be triggered. By default render() will be called for any state change, this method can be used to override the default behavior and prevent re-rendering of the component.

The following example uses shouldComponentUpdate() to check the value of the state "counter", compares the previous value of the state and the current value of the state in the shouldComponentUpdate method and return true only when the state value is changed, this will trigger render(). If the state value of counter did not change it returns false and render() will not be called. We can check if render is called by looking at the console, since 'Render called.' is written to the console whenever render() is triggered.

React Component Lifecycle - shouldComponentUpdate

The shouldComponentUpdate life-cycle method is invoked in the update phase before the render(). This method will be invoked when the component receives new state or props, this method can be used to prevent re-rendering of the component. If shouldComponentUpdate returns false then render() will not be triggered. By default render() will be called for any state change, this method can be used to override the default behavior and prevent re-rendering of the component.

This method has access to this.state, nextState, this.props & nextProps, hence we can compare current state/props with next state/props and make a decision if we have to prevent re-rendering of the component. The purpose of this method is to help in preformance optimization by preventing re-rendering of components on specific conditions.

Below is the syntax for shouldComponentUpdate

React Component Lifecycle - getSnapshotBeforeUpdate

The getSnapshotBeforeUpdate life-cycle method is invoked before the DOM is updated. We can use this method to capture any settings / position information from the DOM before it gets updated. We can pass value from this method to the componentDidUpdate life-cycle method as a third parameter. Any value returned from this method will automatically be passed to the componentDidUpdate method.

Tuesday, August 14, 2018

componentWillReceiveProps example

The componentWillReceiveProps life-cycle method is used to check any change in prop values and update the state of the component if required. This life-cycle method has access to both the previous set of props and new set of props hence we can compare them and update the state if required.

The componentWillReceiveProps life-cycle method will get deprecated, React 16.3 introduced a new life-cycle method getDerivedStateFromProps, which should be used to check prop value changes going forward.

The following example uses componentWillReceiveProps() to check the value of the prop "parentColor", compare the previous value of the prop and the current value of the prop and updates the state if the prop was changed. Any change in state value updates the color of the box displayed in the UI.

getDerivedStateFromProps example

The getDerivedStateFromProps life-cycle method is invoked before calling the render method, both during the initial mounting phase and the update phase. This method returns an object which will be updated in the components state, if no state change is required this method returns null.

The following example uses getDerivedStateFromProps() to check the value of the prop "parentColor", compare the previous value of the prop (saved in the state variable prevColor). If the prop value is different from the previous value then the state value of "bgColor" is updated, which in-turn updates the color of the box displayed in the UI.

React Component Lifecycle - getDerivedStateFromProps

The life-cycle method is invoked before calling the render method, both during the initial mounting phase and the update phase. This method returns an object which will be updated in the comgetDerivedStateFromProps ponents state, if no state change is required this method returns null. The main purpose of this method is to update the state based on changes to props.

This is a new life-cycle method introduced in React 16.3, intended to replace the legacy life-cycle method componentWillReceiveProps. This life-cycle method can be used for purposes like displaying Transition animation by comparing previous and next props, handle dynamic scrolling by using previous and next props to decide whether to scroll up or down. This method get called for every render, hence if possible we should avoid using this method with other alternatives.

This life-cycle method is static, hence it does not have access to "this" and we cannot access this.state inside this method, hence it provides the previous state in its 2nd parameter.

Below is the syntax for getDerivedStateFromProps

Sunday, August 12, 2018

ComponentDidMount example

The componentDidMount life-cycle method is the last lifecycle method executed in the component mounting phase. componentDidMount() is invoked immediately after the component is mounted.

The following example uses ComponentDidMount() to alter the state property "title", in this example we will not make any api calls, but will use setTimeout() to inject a 1 second delay in setting the state. The state change will re-trigger render() and the updated state will be displayed in the browser.

React Component Lifecycle - componentDidMount

The componentDidMount life-cycle method is the last life cycle method executed in the component mounting phase. componentDidMount() is invoked immediately after the component is mounted.

Any initialization to the component which requires the DOM nodes should be done in this method. In this method we can perform activities which require DOM layout like measuring DOM element size etc. We can also alter the state based on the DOM element / layout.

React Component Lifecycle - Render

The Render is one of the important life-cycle methods in the React component life cycle. The render is a mandatory method in a Component.

The render() method should be pure, i.e it should not modify the state (should not call setState()), it should return the same result each time it is invoked. The render method should not modify the state because, changing state will again trigger render(), this will continue as a cycle and cause an indefinite loop causing the application/browser to crashes.

Below is a basic render method of a React component.

React Component Lifecycle - Constructor

The constructor is the first life-cycle method invoked when a React component is mounting / initializing. The following code snippet shows a basic constructor for a React component with state initialization and event binding.

Saturday, August 11, 2018

React Component Lifecycle Error Handling

When an error occurs while rendering a react component or when an error occurs anywhere in the components life-cycle method or in the constructor of any of its child components the following life-cycle method is invoked.

componentDidCatch()

React Component Lifecycle UnMounting

When a React component is unmounting, i.e when the component is removed from DOM, the following lifecycle method is invoked.

componentWillUnmount()

React Component Lifecycle Updating

When a React component is updating the following life cycle methods are invoked in the specified order. An update to a React component can be caused by a change in its state or props or by calling forceUpdate()

static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()

React Component Lifecycle Mounting

When a React component is mounting / initializing the following life-cycle methods are invoked in the specified order.

constructor()
static getDerivedStateFromProps()
render()
componentDidMount()

What is React Component Lifecycle

React applications are composed of Component, each component has several “life-cycle methods” that you can override to alter the behavior of the components.

There are some updates to the component life-cycle methods in React 16.3.
3 of the existing component lifecycle methods will depreciate and 2 new methods are introduced.

The following life cycle methods will eventually depreciate. These methods will continue to work till React 17.0

Friday, August 10, 2018

forwardRef Refs example in React

Ref forwarding is an approach by with React allows us to create a Ref in a parent component and forward the same to a nested child component. The forwarded ref is attached to a DOM node in the child component, once it is attached the parent component can have direct access to the DOM node in the child component.

Ref forwarding typically not necessary for most components in the application, since React components hide their implementation details, including their rendered output. However the forwardRef approach can be used for features like setting focus, clearing text etc.

In the below example we create a ref "myRef" in the parent component and pass the same to "ChildComponent", this component attaches the ref to a text-box. The parent component can now access the value in the text-box using this.myRef.current.value. In this example we have a button in the parent component, on clicking the button we get the value from the text-box and display it in the parent component.

Thursday, August 9, 2018

Callback Refs example in React

Callback Refs is one another way of implementing refs in React. in callback Refs we pass a function as a ref, instead of an attribute created using createRef(). The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.

Callback Refs are supported in React 16.3 and also in older versions.

In this example we shall see on how callback Refs can be used to get the value entered in a text-box control. The ref "myCallbackRef" is used to get the value from the text-box and set it to the state.

createRef API example in React

Refs allow us to access DOM elements or react elements which belong to a different parent component. The React.createRef API from React 16.3 provides us a structured way to handle refs instead of the conventional string refs

In this example we shall see on how createRef API can be used to get the value entered in a textbox control. The ref "myCreateRef" is used to get the value from the textbox and set it to the state. From React 16.3 onwards the new createRef API should be used instead of the string refs, though string refs are still supported it is recommended to use createRef API going forward. The string ref will eventually get deprecated.

Wednesday, August 8, 2018

string refs example in React

refs in React provides a way to access DOM node / React element directly. refs have a performance impact, hence refs should be avoided if the same functionality can be achieved using other means like state or event handlers. refs can be used for simple features like setting focus, getting text value from input controls etc.

In this example we shall see on how refs can be used to get the value entered in a text-box control. to pass props in a parent component and pass it to the child/nested component. The ref "myRef" is used to get the value from the text-box and set it to the state.

props example in React

props or properties in React is a way in which we can pass data between components in a React page. Usually props are passed from the parent component to the child/nested components.  props are immutable they are passed from the parent/container component to the child components.

In this example we shall see on how to pass props in a parent component and pass it to the child/nested component.

Tuesday, August 7, 2018

Event handler example in React

Event handlers are used to handle various events arising from controls in React components. Event handlers are functions in react component, event handlers are bound to events in React components in the constructor or the component using bind()

this.handleClick = this.handleClick.bind(this);

In this example the react component has a buttons, the click event of the button is bound to a handler function handleClick(). In the handler we change the state of the component.

setState example in React

The setState() method is used to change the state values of a React Component. After the component is initialized we can call setState to change specific state properties, setState() updates the components state and triggers Render() of the component. Based on the updates in state the component in re-rendered.

In this example we will initialize a component with a property show with default value false. We have a button Show/Hide the click event of the button toggles the value of the state using setState(), based on the current value of the state property the component will show/hide the message "Hello State".

state example in React

State in a React Component is the components data store, all data required by the component are stored in the components state. State is nothing but a JavaScript object with properties to store each state value. The initial state of the component is set on the constructor of the component. using this.state = {}. After initializing the state can be changed using setState().

In this example we will have a time property in the state which will be displayed in the component. When the component initializes the time property is set to the current date/time and the time is displayed in the component.

Parent - Child components example in React

We have so far seen some simple components which don't have a parent - child relationship, but when we create larger page we cannot implement the full application in a single component. Large page often have a root parent component and multiple levels of child components each acting like a widget in the parent component. In this example we shall see on how to embed child components into a parent component and render the output from both the components.

In this example we will have 2 separate files for the parent and the child components, we will import the child component into the parent component and display the child component in the parent components render method.

Friday, August 3, 2018

Functional stateless component example in React

In the previous examples we have seen that we use the 'class' keyword and extends React.Component syntax for creating a React component. This syntax is required for creating a regular React component will full feature support like state, refs, lifecycle methods etc. If we need to create simple components which don't need these features we can create simple Functional stateless components using a simpler syntax.

Functional components don’t support state, refs, or lifecycle methods, in the below example we can see that there is no reference to this.state or the class keywords.

Inline styles without classes example in React

There are different ways of adding styles to react components.
1. Inline styles.
2. CSS Stylesheet
3. CSS Modules

In this example we shall see on how to implement Inline styles in React components, without defining style classes. The style elements will be directly defined in the html tags of the react component, there will be no reference to inline or external style classes. This approach is a quick way to apply styles but not recommended for larger projects since the styles are not centralized but defined across the components making it difficult to modify and maintain.

CSS Module styles example in React

There are different ways of adding styles to react components.
1. Inline styles.
2. CSS Stylesheet
3. CSS Modules

In this example we shall see on how to implement styles using a CSS Modules in React components. The example uses styles defined in a seperate .css file and imported into the react component file.

Inline styles example in React

There are different ways of adding styles to react components.
1. Inline styles.
2. CSS Stylesheet
3. CSS Modules

In this example we shall see on how to implement Inline styles in React components. The example uses styles defined in the same file as the react component and the style is applied to the component using className="<style name>"

Thursday, August 2, 2018

Basic Component example in React

This example is similar to the previous HelloWorld example, except that we will use a seperate file for the HelloWorld react component.
The example contains 3 files index.html, index.jsx and HelloWorld,jsx

The index.html is the template file into which the react component will be loaded.
The index.jsx file contains the ReactDOM.render() which loads the React component in the HTML template.
The HelloWorld.jsx file is the React component file which contains a HelloWorld component.

Apart from these files we will need to setup the environment to take care of compiling the .jsx files and rendering the component to the browser. For this example am using a "webpack-react-boilerplate" which takes care of setting up the environment so that we can focus on the actual example.

Basic HelloWorld example in React

Let us start the looking into React with some basic examples, as always we will start will a very basic Hello World example.
This example just displays a string "Hello World" in the browser. The example contains 2 files index.html and index.jsx.

The index.html is the template file into which the react component will be loaded.
The index.jsx file is the React component file which contains a HelloWorld component.

Apart from these files we will need to setup the environment to take care of compiling the .jsx files and rendering the component to the browser. Setting up the environment will be an overkill for this basic example hence we will skip that part. For this example am using a "webpack-react-boilerplate" which takes care of setting up the environment so that we can focus on the actual example.

Let us now look into the example files.

Wednesday, August 1, 2018

What's new in React 16.3

React 16.3 introduces the following new features
  1. Context API
  2. createRef API
  3. ref Forwarding
  4. new Component Lifecycle Changes
  5. StrictMode
Let us now look into these features in detail.