Getting started with react js

Introduction

React JS is one of the most talked about front end frameworks of 2015. Facebook initially promoted it as “just the V in MVC” or “just the view layer” but I can assure you that it is much more than that. A lot of positive news has been around react for almost a couple of years now. To mark the stability of this library, facebook engineers promoted it from version 0.14, directly to version 15 (Noting that there is no missed 0 here, it is fifteen indeed).

Basics

So what makes react so famous ?

The reason is that it makes code more declarative and easier to reason about. In simplest terms, react can be summed up as follows

UI = function(data)

This is it, this is how React JS works. It works on a set of data and when the data changes, it re-renders whole UI again. This might sound trivial and naive at first but think of how easy programming becomes with this model. All you have to take care of is a single data store and UI is automatically transitioned for you.

You might be wondering that this won’t be performant. Well, that is where facebook’s team of engineers kick in and make it fast.

This is the algorithm behind React JS: https://facebook.github.io/react/docs/reconciliation.html

Following are the terms you will come across very often while working with React.  If you understand all of them and their purposes, you’ll be at a very good spot after reading this tutorial.

  • JSX — Allows us to write HTML like syntax which gets transformed to lightweight JavaScript objects.
  • Virtual DOM — A JavaScript representation of the actual DOM.
  • createClass — The way in which you create a new component.
  • render (method) — What we would like our HTML Template to look like.
  • render — Renders a React component to a DOM node.
  • state — The internal data store (object) of a component.
  • getInitialState — The way in which you set the initial state of a component.
  • setState — A helper method for altering the state of a component.
  • props — The data which is passed to the child component from the parent component.
  • propTypes — Allows you to control the presence, or types of certain props passed to the child component.
  • getDefaultProps — Allows you to set default props for your component.
  • Component LifeCycle
    • componentWillMount — Fired before the component will mount
    • componentDidMount — Fired after the component mounted
    • componentWillReceiveProps — Fired whenever there is a change to props
    • componentWillUnmount — Fired before the component will unmount
    • And more….
  • Events
    • onClick
    • onSubmit
    • onChange
    • And more….

The above information might be overwhelming at first but remember that at this point you should understand, on a very high level, how React works.

Dive into code

Let us start in the traditional way of learning anything new in programming. By creating a HelloWorld component.

In this section we will learn about React.createClass function to create a simple component.

Here is a live code link of the below code: https://jsfiddle.net/divyenduz/km0dsft5/

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

ReactDOM.render(<HelloWorld />, document.getElementById('app'));

The only method on the object we’re passing to createClass is the render method. Every component is required to have a render method. Render function is the template of a component. The other React specific thing in this code is ReactDOM.render. This function takes in two arguments. First is the component you want to render, the second argument is the DOM node where you want to render the component.

The the above code we use ReactDOM.render to load HelloWorld component and render it to DOM.

Many programmer initially find it weird and alienating to put “HTML” like code (JSX) in JS.

Because all the web developers are taught otherwise but this is where React’s philosophy of rethinking best practices creeps in.

http://2013.jsconf.eu/speakers/pete-hunt-react-rethinking-best-practices.html

Stateful Component

The next thing we will be exploring is React’s setState function. Remember how I initially summed up React JS with this function.

UI = function(data)

setState function is essentially the way for us to tell a react component that the underlying data has changed and it needs to re-render the UI. Here is an example explaining all this.

Live code: https://jsfiddle.net/divyenduz/xjm1k7u0/

var HelloUser = React.createClass({
  getInitialState: function(){
    return {
      username: '@tylermcginnis33'
    }
  },
  render: function(){
    return (
      <div>
        Hello {this.state.username}
      </div>
    )
  }
});

The first new method to take a note of here is getInitialState method. As the name suggests getInitialState functions is used to render the initial state of your component. This function gets us the initial value of data in our UI function. Based on the data returned from this function our initial UI will be rendered.

I the above example we have configured out component to keep track of a username value. This variable can be used inside any function of our component by {this.state.username}, which is what we are doing in render function.

The next function we would talk about in this section is setState. Using this function we can change the value of data in our UI function, remember that UI is rendered as

UI = function(data)

setState is the hook provided to us by React to change the value of this data and re-render the UI.

This way this works is that we use setState to notify our component that some data has changed→ which leads to re-render of virtual DOM, which leads to a diff between previous virtual DOM and new virtual DOM, post which only update in real DOM is the necessary changes, this is the core concept of react that makes it very very performant.

Component composition

Now we will look at the final code assignment of this tutorial. In this assignment we will compose two components and pass information between them.

Live code: https://jsfiddle.net/divyenduz/2p0kyf5w/

Parent component:

var FriendsContainer = React.createClass({
  getInitialState: function(){
    return {
      name: 'Tyler McGinnis',
      friends: ['Jake Lingwall', 'Murphy Randall', 'Merrick Christensen']
    }
  },
  render: function(){
    return (
      <div>
        <h3> Name: {this.state.name} </h3>
        <ShowList names={this.state.friends} />
      </div>
    )
  }
});

 

Child component:

var ShowList = React.createClass({
  render: function(){
    var listItems = this.props.names.map(function(friend){
      return <li> {friend} </li>;
    });
    return (
      <div>
        <h3> Friends </h3>
        <ul>
          {listItems}
        </ul>
      </div>
    )
  }
});

Above mention code as two different components. One is ShowList component which will serve as the child component and the other is FriendsContainer which will serve as the parent component. As their names suggest, FriendsContainer contains a list of friends which it passes on to the ShowList component by a method we call props. Props are React’s way of passing information between composed components. You can pass any basic JS object as a prop which is not but a JSX attribute and access in the child component like {this.props.varName} which is exactly what we have done in Show list by accessing names variable like {this.props.name}.

Further reading

I hope this tutorial was informative for you. I will provide a list of references that can be used to build on from here.

  1. The official documentation is top notch and up to date
    https://facebook.github.io/react/
  2. The egghead.io course on react fundamentals (some content may not be free)
    https://egghead.io/courses/react-fundamentals
  3. Things about react every beginner should know
    https://camjackson.net/post/9-things-every-reactjs-beginner-should-know

 

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.