Intro to ReactJS

React is a new JavaScript Library to efficiently write the User Interface. It is also considered V in MVC architecture

Intro to ReactJS
Intro to ReactJS

React is a new JavaScript Library to efficiently write the User Interface. It is also considered V in MVC architecture.

React introduces JSX; a new way to write HTML in JS. With the help of Virtual DOM, it reduces the DOM access and Manipulation frequency efficiently.

This ends up with really simple and highly efficient View Library. So today we will be covering intro to ReactJS.JSX can be compiled at server with Node or at browser. JSX compiled on server is much faster rather than on Client side.

React enforces one way data binding, which will help in easy reasoning of data flow. It’s one directional, so it’s easy to point out the faulty code and correct it.

To create React Components and use them in your WebApps, you need React and React-DOM. Though the use of react-dom is optional. React-DOM will give you ease DOM related capabilities for you react application.

Other platforms can be server side or mobile apps. For server side, same DOM related techniques can be used; though for Mobile apps, we will need to use react-native along with React.

The React components are easy to code and consumable. To keep the UI fast and efficient, React also provides some patterns and anti-patterns which; if followed; will definitely produce great UIs.

The benefits of using React can be:

  • CSS Scoping issues solved
  • Component are ready to consume
  • Data Flow is unidirectional, which allows to track errors quickly
  • Can be used in small parts of Project also

Creating Views/Components with React:

To create react components, JSX would help us much. And as we move forward in creating React components, the code will be adopting the ES6 standard also to speed up the development and execution.

Following will be the parts of the component that will be needed most of the times:

Component Creation

React.createClass

All the components get initialized with React.createClass constructor method. This constructor method accepts an object with one key named as render method.

var CommentBox = React.createClass({ render: <div>Hello World</div> });

render()

This method will return the component’s HTML or View. This returned code is a mix of XML and JavaScript; and hence it is called as JSX. The JSX can have JS mixed in between the XML called as expressions.

var CommentBox = React.createClass({ 
  render: function(){
    return <div>Hello World</div>;]
  }
});

Member Objects

All these objects are part of React Component. In the descriptions of the objects, the component is referred by this and will subject to the execution context.

state

React Components can maintain state. And for that state, the state object of component is useful.
This object can be accessed by this.state and all the state objects are under this object.

var CommentBox = React.createClass({ 
  render: function(){
    console.log( this.state );
    return (
        <div>Hello World!</div>
      );
  }
});

props

You can access to React Component’s attributes with this object. E.g.

var CommentBox = React.createClass({ 
  render: function(){
    console.log( this.props );
    return (
        <div>
        {this.props.greeting}, Hello World!
        </div>
      );
  }
});
ReactDOM.render(
    <CommentBox greeting='Good Morning' />,
    document.getElementById('app')
);

From above code, the attribute greeting can be accessed with this.props.greeting in the functions of component.

refs

You can create references to the DOM nodes in the React component by ref attribute inside element. And that reference will be accessible inside the this.refs object. E.g. if for an input element ref=’username’ is set, this can be used inside the event handlers with this.refs.username.
This will give access to the DOM node, and furthermore to get the value from that input box, this.refs.username.value can be used.


Component State

getInitialState()

This method is a Component Lifecycle Method and is the entry point for the state to initialize. In this method, you can write the code to initialize the state of component in the life cycle of component. For example, following code will show how to create initial state.

getInitialState: function(){
  return {
    comments: [],
    user: { name: 'Time to Hack', url: 'https://time2hack.com'}
  };
}

setState()

This method can be used inside any method in component to change the state of the component and hence causing the component to re-render. Re-render will be based on the diff to virtual-DOM and actual-DOM. In this method, you can the new partial object hierarchy. That hierarchy will be merged to state object of the component.

this.setState({
    user: {
        name: 'Pankaj Patel', 
        url: 'http://pankaj.pro'
    },
});

replaceState()

This method can also be used inside any method in component to change the state of the component and hence causing the component to re-render. Unlike setState, this will replace the complete state object instead of merging. So for following example, the comments array will not exist in the new state.

this.replaceState({
    user: {
        name: 'Pankaj Patel', 
        url: 'http://pankaj.pro'
    },
});

Component Lifecycle Methods

Mount

These methods will be called during the mounting process of component.

componentWillMount()

This method will be called immediately before the mounting of the component.

componentWillMount: function(){
    console.log('Initializing component');
    //Do some stuff before loading
    if( !window.components ) {
        window.components = {}
    }
    window.components[ this.displayName ] = { 
        name: this.displayName, 
        status: 'loading' 
    };
}

componentDidMount()

This method will be called immediately after the mounting of the component.

componentDidMount: function(){
    console.log('Initialized component');
    //Do some stuff after loading
    window.components[ this.displayName ].status = 'loaded';
}

Update

These methods will be called while updating the component.

componentWillReceiveProps()

This method invoked when component is receiving new props. The new props are received as an object type in form of method argument. This method is not for initial ‘render’.

So this method can be used to transform the state as per the new props. Old props are still accessible inside this method via this.props.

For example, CommentBox component has user login and if user logins, the component property loggedin gets updated to true. So on that moment, it is not needed to ask for User’s name and email. So the same can be updated in state with this method.

componentWillReceiveProps: function(newProps){
    console.log('Component receiving new props');
    //Do changes in state as per new props
    if( this.props.loggedin != newProps.loggedin && newProps.loggedin ) {
        this.setState( { user: newProps.name, url: newProps.url } );
    }
}

shouldComponentUpdate()

This method will be called before re-rendering of component when new state or new props are received. The newProps and newStates? are passed as a parameter to this method and this method will return a boolean value. If it returns false, the component will not update and the call to next methods in component’s lifecycle are not called.

shouldComponentUpdate: function (nextProps, nextState) {
    console.log('Checking if component should update');
    if( this.props.loggedin != newProps.loggedin ) {
        return true;
    } else {
        if( this.state.user != newState.user ) {
            return true;
        }
    }
    return false;
}

componentWillUpdate()

This method will be called immediately before the re-render of the component.

componentWillUpdate: function(){
    console.log('Updating component');
    window.components[ this.displayName ].status = 'rendering';
}

componentDidUpdate()

This method will be called immediately after the re-render of the component.

componentDidUpdate: function(){
    console.log('Updated component');
    window.components[ this.displayName ].status = 'rendered';
}

Unmount

This method will be called while un-mounting the component.

componentWillUnmount()

componentWillUnmount: function(){
    console.log('Unmounting component');
    window.components[ this.displayName ].status = 'removed';
}