intor_react
2019 17 Sep

Introduction to React JS and Components

React is a flexible JavaScript library for building user interfaces and it lets you compose complex UIs from small and isolated pieces of codes which is known as Components. React has the aim to simplify the development of visual interfaces.

Developed by Facebook and was released to the world in 2013. It is already powering the two most common social giant Facebook and Instagram and other companies like Uber etc. Recently Microsoft also adopted React to integrate user chat systems in their office products.

WHY REACT?

React has taken the front-end development world by storm. Below are the key points for that:

  1. Less complex: Before React, Ember.js and Angular 1.x were the main choices for the JavaScript developers. Too many conventions on the code and also two frameworks brought too much to the table. While React decided to only stick with the view layer instead of the full MVC framework. Also moving from Angular 1.x to 2.x was like moving in a different framework. Along with this fact, execution speed that was promised by React, which makes developers to eager to try.

  2. Component-Based: React is component-based. A component is a small piece of code that can be reused multiple numbers of times. It can be stateless or stateful. For example, it can be a header, footer or can be a small element like button on a webpage. We will go into depth later in this article. Below is the example of a normal class-based React component:
    class Homepage extends Component {
      render() {
        return (
          <div>
            <p>Welcome to React Demo </p>
          </div>
        );
      }
    } 

     

  3. JSX: Another interesting fact of using React is `JSX`. JSX stands for JavaScript Extension and is a react extension allowing a developer to write JS which looks like HTML. It also allows writing ES6 and ES7 codes using JSX. When you are writing in JSX then you need to pay attention to a few things. For example. `class` is JS reserved word so instead of `class`, you have to write `className`. For the same `for` becomes `htmlFor`.
    <h1 id={myId} className={ myClass }>Hello, world!</h1>
    

     

  4. Virtual DOM:  Virtual DOM is a tree of nodes that lists elements and their attributes and content as objects and properties. React provide render() method which creates a node tree from the available components and updates it in response to data mutation caused by actions. Whenever data is changing, that particular stateful component re-render and React create a virtual DOM representation for that. Using `diff` algorithm it calculates the actual difference between old and the new virtual DOM and then updates the real DOM with what has changed, which makes React faster than others.

  5. Backed by Facebook: React is backed by Facebook. It benefits a project if it turns out to be successful. It is an open-source project and used in over 2 million projects. 

 

React Component

Before starting, it is a good idea to understand the building blocks of the React and that is Component. It is a typical JavaScript class or can be a JavaScript function that returns an element. Have a look at the below snippet:

class Login extends Component {
    
    render () {
        return (
            <div className='container-custom'>
                React Class based Component
             </div>
        )
    }
}

Above is an example of a class base component is a typical JS class that has render method which is returning <div> element.

const  Login = () => {
    return (
        <div className={'functional_component'}>
            Functional Component
        </div>
    )
}

Above is an example of a functional component which is typical JS function and returning an <div> element.

A functional component is useful for static element rendering which does not contain logic like event handlers. On the other hand, if your element is dynamic and based on logic then the class base component is useful. A class base component also has its state where a component can store its value. A class base component has a life cycle method which is not available for a functional component.

Component Life Cycle

React component’s life cycle is divided into three sections. Initial render, update and unmounting.

Initial Render or Mounting: 

  1.   Initialization: In this phase first thing gets called is component’s constructor where the developer has to define props and states. The following code snippet describes the initialization process.
     constructor(props){
        super(props);
        this.state = {
          loading: false
        }
      }

    Passing props in a constructor and super are required when you have to use props within a constructor. This phase is optional, and this phase is not applicable for a functional component as they don’t have any lifecycle method. 

  2. getDerivedStateFromProps: After successful initialization, this lifecycle method gets invoked. As this is a static method you cannot use this keyword inside this method. Below is the snippet:
     static getDerivedStateFromProps(props, prevState){
        return {
          cachedSomeProp: props.someProp
        }
      }

    Within this method, you will have access to the new props and the previous state as a parameter. If you need to change the component state then you can simply return it as an object or if not then simply return null.

  3. componentDidMount: After successful rendering of the component this lifecycle method gets invoked. This method ensures that the component is successfully rendered on the DOM. Below snippet is the example of this life cycle:
     componentDidMount(){
        this.props.decrement()
     }
    This is the best place to call API or make an asynchronous request.   

Updating

  1. getDerivedStateFromProps: Yes, this lifecycle method called again. After changes on the state, component re-rendered and on every update, this method gets invoked. This is very much useful if you want to change the state based on new props. Have a look on below snippet:
    static getDerivedStateFromProps(props, state){
        if(state.images.length > 0){
          return {}
        }
        return {images: props.attributes}
     }
  2. shouldComponentUpdate: React’s render method gets called on every props and state changes. But if you are worried about wasted renders then this lifecycle method is great things to you. This method usually asks for permission before re-render. This method usually returns boolean true or false. Below is the example snippet:
     shouldComponentUpdate(nextProps, nextState) {
        // only update if no of images change
        return nextState.images.length > this.state.images.length;
      }

  3. render: After changes on state and if shouldComponentUpdate allows then this method gets invoked and re-render the component in the DOM.

  4. getSnapshotBeforeUpdate: This lifecycle method gets invoked after render and before updated to actual DOM. It becomes handy when you need to grab some DOM information just after an update is made. The value of DOM in this method is available is just before DOM is updated.

  5. componentDidUpdate: After new changes are committed to the actual DOM this lifecycle method is gets invoked. This method ensures that your component is updated successfully.
    componentDidUpdate(){
        // do your task here
    }

 

Unmounting

  1. componentWillUnmount: This lifecycle method gets invoked before the component is finally unmounted from the DOM. If you have any component-specific event listener, then it is the best place to remove that. Below is the snippet of this method:
    componentWillUnmount(){
        this.clearListner()
    }

 

Conclusion

In this article, I have covered basic React, component lifecycle, virtual DOM, state and props, etc. To start with React, it is better to use `create-react-app` template as it comes Babel, Webpack, react, react-dom pre-configured. Working with React you will have other advantages like React Native and React VR.
 

Latest Blogs

Security

Tips to Secure your Drupal Website with Ease: Basic Security checklist

If someone were to break in your room, they would probably learn less about you than if they hacked you on the internet.

Read More

intor_react

Introduction to React JS and Components

React is a flexible JavaScript library for building user interfaces and it lets you compose complex UIs from small and isolated pieces of codes which is known as Components.

Read More

Flexbox

How to simplify the layout of your website using Flexbox?

Have you ever scratched your head while working with CSS to make some simple layouts for your website? Are you fed up of running to the UI developers for small layout designs every time?

Read More

cache_context

Drupal 8 Cache Context: An efficient way for context based caching.

We are well aware of the fact that Drupal Cache API is a remarkable feature introduced in Drupal 8.

Read More