DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. React.js Essentials
refcard cover
Refcard #224

React.js Essentials

The Simple Front-end Library for User Interfaces

Gives you the essentials of React.js, from the architecture to the virtual DOM, from building components to styling them.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Hemanth HM
FullStack Developer, FOSS
Table of Contents
► What Is ReactJS? ► How the Magic Happens ► A Simple "Hello" Component ► Component Specifications: ► AJAX Requests ► Styling Your Components ► DOM Helpers ► Conventions for React DOM & JSX ► The Flux Application Architecture ► React v0.14 ► Testing Your Application With Jest
Section 1

What Is ReactJS?

React (a.k.a. ReactJS or React.js) is a JavaScript library for creating user interfaces, open sourced to the world by Facebook and Instagram team in 2013. One might think of it as the “View” in the “Model-View-Controller” pattern.

React’s main goal is to be simple, declarative, and compassable, as it is intended to ease the process of building large applications using data that changes over time.

React was created by Jordan Walke, a software engineer at Facebook, with the influence of XHP, a PHP-based component system that is still in use at Facebook, but also by functional programming ideas. Pete Hunt wanted to use React at Instagram, so he pushed to extract React from Facebook-specific code and open source it. (Editor's note: Some have expressed concern about the React license; see discussions here, here, and most recently (Jan2016) here, with discussion of some alternatives here. We're not lawyers but figure it's important to be aware of this sort of thing.)

React has lately gained a lot of popularity for its concept of a “virtual-DOM,” which allows it to determine which parts of the DOM have changed by diffing the new version with the stored virtual DOM, and using the result to determine how to most efficiently update the browser's DOM.

Section 2

How the Magic Happens

To get an idea of what’s going on inside React, take a look at the following diagrams demonstrating how React.js rendering and the React Virtual DOM work:

Image title

Figure 1: React.js Rendering

Image title

Figure 2: The React Virtual DOM

React basically batches DOM updates and then applies minimal diffs to the real DOM.

Section 3

A Simple "Hello" Component

React components implement a render() method that takes input data and returns what to display.

Here is a simple example of a "Hello" Component:

7
1
var Hello = React.createClass({
2
  render: function () {
3
    return <div>Hello {this.props.name}</div>;
4
  }
5
});
6
​
7
React.render(<Hello name="World" />, document.body);

Note: The XML-like syntax is called JSX.

Here's the same component without JSX:

​x
1
var Hello = React.createClass({displayName: "Hello",
2
  render: function() {
3
    return React.createElement("div", null, "Hello ", this.props.name);
4
  }
5
});
6
​
7
React.render(React.createElement(Hello, {name: "World"}), mountNode);
Section 4

Component Specifications:

render

The render() function should be pure, meaning that it does not modify the component state. It should examine this.props and this.state and return a single child element.

getInitialState

Invoked once before the component is mounted. The return value will be used as the initial value of this.state.

getDefaultProps

Invoked once and cached when the class is created. Values in the mapping will be set on this.props.

propTypes

The propTypes object allows you to validate props being passed to your components.

mixins

The mixins array allows you to use mixins to share behavior among multiple components.

statics

The statics object allows you to define static methods that can be called on the component class.

displayName

The displayName string is used in debugging messages. JSX sets this value automatically.

Components API

setState

Merges nextState with the current state.

replaceState

Like setState(), but deletes any pre-existing state keys that are not in nextState.

forceUpdate

Call render() on the component, skipping shouldComponentUpdate()

 React.findDOMNode (0.13+)

Returns the corresponding native browser DOM element.

isMounted

isMounted() returns true if the component is rendered into the DOM.

setProps

To change the properties and trigger re-render

replaceProps

Like setProps() but deletes any pre-existing props instead of merging the two objects.

Lifecycle Methods

componentWillMount

Invoked once, both on the client and server, immediately before the initial rendering occurs.

componentDidMount

Invoked on the client immediately after the initial rendering occurs.

componentWillReceiveProps

Invoked when a component is receiving new prop. Use setState() here.

shouldComponentUpdate

Invoked before rendering when new props or state are being received. Skips render() if returns false.

componentWillUpdate

Invoked immediately before rendering when new props or state are being received. Can’t use setState() here.

componentDidUpdate

Invoked immediately after the component's updates are flushed to the DOM. Operate on the DOM here.

componentWillUnmount

Invoked immediately before a component is unmounted from the DOM.

States and Properties

Props and states are both plain JS objects; a change within one of them will trigger a render. These objects are deterministic.

12
1
<VideoComponent fullscreen={true} />
2
// props
3
  this.props.fullscreen //=> true
4
// state
5
  this.setState({ user: 'hemanth' });
6
  this.replaceState({ ... });
7
  this.state.username //=> 'hemanth'
8
  render: function () {
9
    return <div className={this.props.fullscreen ? 'full' : ''}>
10
      Hello, {this.state.username}
11
    </div>;
12
}

Pre-populates states and props:

8
1
React.createClass({
2
  getInitialState: function () {
3
    return { comments: [] };
4
  },
5
  getDefaultProps: function () {
6
    return { name: "Hello" };
7
  }
8
);

Deciding when to use props and went to use state might get tricky. The following table will help to simplify this decision:

Deciding factor

props

state

Can get initial value from parent Component?

Yes

Yes

Can be changed by parent Component?

Yes

No

Can set default values inside Component?

Yes

Yes

Can change inside Component?

No

Yes

Can set initial value for child Components?

Yes

Yes

Can change in child Components?

Yes

No


Section 5

AJAX Requests

React by default doesn’t provide a helper method to manage AJAX requests, but you can use any other third party JavaScript library—like jQuery or Zepto—to make necessary AJAX requests.

Below is a sample code snippet that performs an AJAX request on props.url and on success sets the data state. In case of  an error, it just uses console.error to report the error.

Note: Make sure that the execution context (this) is bound to the success and error callbacks.

13
1
componentDidMount: function() {
2
    $.ajax({
3
      url: this.props.url,
4
      dataType: 'json',
5
      cache: false,
6
      success: function(data) {
7
        this.setState({data: data});
8
      }.bind(this),
9
      error: function(xhr, status, err) {
10
        console.error(this.props.url, status, err.toString());
11
      }.bind(this)
12
    });
13
  }
Section 6

Styling Your Components

In React, styles are mentioned in line, but unlike the traditional way of inline CSS strings, here we specify each style as an object whose key is the camelCased version of the style name, and whose value is the style's value (usually a string).

7
1
var divStyle = {
2
  color: 'white',
3
  backgroundImage: 'url(' + imgUrl + ')',
4
  WebkitTransition: 'all', // note the capital 'W' here
5
  msTransition: 'all' // 'ms' is the only lowercase vendor prefix
6
};
7
React.render(<div style={divStyle}>Hello World!</div>, mountNode);

Most numeric values at the end of a style prop receive an automatic “px” specification added to them (e.g., “width: 10” is read as “width: 10px”). Here is a list of properties that won't get the automatic "px" suffix:

  • boxFlex

  • boxFlexGroup

  • columnCount

  • fillOpacity

  • flex

  • flexGrow

  • flexPositive

  • flexShrink

  • flexNegative

  • fontWeight

  • lineClamp

  • lineHeight

  • opacity

  • order

  • orphans

  • strokeOpacity

  • widows

  • zIndex

  • zoom

Section 7

DOM Helpers

References

Helps to access the DOM nodes.

9
1
<input ref="firstName">
2
this.refs.firstName
3
React.findDOMNode(this.refs.firstName).focus()
4
React.findDOMNode(this.refs.firstName).value
5
DOM Events: Helps to handle DOM events.
6
<input type="text" value={this.state.value} onChange={this.handleChange} />
7
handleChange: function(event) {
8
  this.setState({ value: event.target.value });
9
}

Two-way data bindings with mixins

5
1
Email: <input type="text" valueLink={this.linkState('email')} />
2
React.createClass({
3
  mixins: [React.addons.LinkedStateMixin]
4
});
5
this.state.email

Validating properties

Primitive types: .string, .number, .func, and .bool.

React elements: .element, .node.

Enumerables: .oneOf, .oneOfType.

Arrays and objects: array[Of], .object[Of], .instanceOf, .shape.

Sample usage:

5
1
React.createClass({
2
  propTypes: {email: React.PropTypes.string, firstName: React.PropTypes.string, age:  React.PropTypes.number, gender: React.PropTypes.oneOf(['M','F','NA']) 
3
    node: React.PropTypes.node, cb: React.PropTypes.func.isRequired,
4
  }
5
});

Custom Validation

4
1
propTypes: {
2
  customProp: function(props, propName, componentName) {if (!/matchme/.test(props[propName])) {return new Error('Validation failed!');}
3
  }
4
}

React Addons

React.addons are useful utilities for building React apps, these are currently experimental, and not yet part of Core React.

  • TransitionGroup and CSSTransitionGroup, for dealing with animations and transitions

  • LinkedStateMixin helps in two way data binding.

  • cloneWithProps, to make shallow copies of React components and change their props.

  • createFragment, helps to create a set of externally-keyed children.

  • update, helps to deal with immutable data.

  • PureRenderMixin, a performance booster under certain situations.

Apart from these there are few which are available in the development (unminified) version of React only:

  • TestUtils, simple helpers for writing test cases

  • Perf, for measuring performance and giving you hint where to optimize.

To get the add-ons, use react-with-addons.js (and its minified counterpart) rather than the common react.js.

When using the react package from npm, simply require('react/addons') instead of require('react') to get React with all of the add-ons.

  • NOTE: Add-ons have moved to separate packages in React v0.14+:
    • react-addons-clone-with-props
    • react-addons-create-fragment
    • react-addons-css-transition-group
    • react-addons-linked-state-mixin
    • react-addons-perf
    • react-addons-pure-render-mixin
    • react-addons-shallow-compare
    • react-addons-test-utils
    • react-addons-transition-group
    • react-addons-update
    • ReactDOM.unstable_batchedUpdates in react-dom
  • Creating Your Own Mixins

    6
    1
    var TimeOutMixin = {
    2
      componentWillMount: function() { .. }
    3
    }
    4
    var TickTock = React.createClass({
    5
      mixins: [TimeOutMixin]
    6
    }

    React on ES2015/ES6:

    These are experimental and you must use a transpiler for this to work

    Classes

    5
    1
    class Animal extends React.Component {
    2
      render() {
    3
          return <img alt={this.props.name} src={this.props.src} />;
    4
      }
    5
    }

    Property Initializers

    19
    1
    var Video = React.createClass({
    2
      getDefaultProps: function() {
    3
                                        return {
    4
                                        autoPlay: false,
    5
                                        maxLoops: 10,
    6
                                        };
    7
      },
    8
      getInitialState: function() {
    9
                                        return {
    10
                                        loopsRemaining: this.props.maxLoops,
    11
                                        };
    12
      },
    13
      propTypes: {
    14
                                        autoPlay: React.PropTypes.bool.isRequired,
    15
                                        maxLoops: React.PropTypes.number.isRequired,
    16
                                        posterFrameSrc: React.PropTypes.string.isRequired,
    17
                                        videoSrc: React.PropTypes.string.isRequired,
    18
      },
    19
    });

    Arrow Functions

    5
    1
    class PostInfo extends React.Component {
    2
      handleOptionsButtonClick = (e) => {
    3
                                        this.setState({showOptionsModal: true});
    4
      }
    5
    }

    Dynamic property names with template strings

    7
    1
    class Form extends React.Component {
    2
      onChange(inputName, e) {
    3
                                        this.setState({
    4
                                        [`${inputName}Value`]: e.target.value,
    5
                                        });
    6
      }
    7
    }

    Destructuring & spread attribute

    9
    1
    class AutoloadingPostsGrid extends React.Component {
    2
      render() {
    3
                                        var {
    4
                                        className,
    5
                                        ...others,  // all properties of this.props except for className
    6
                                        } = this.props;
    7
                                        return <PostsGrid {...others} />
    8
      }
    9
    }

    CoffeeScript and React [React v0.13.0+]

    13
    1
    div = React.createFactory 'div'
    2
    class Counter extends React.Component
    3
      @propTypes = initialCount: React.PropTypes.number
    4
      @defaultProps = initialCount: 0
    5
      constructor: (props) ->
    6
                                        super props
    7
                                        @state = count: props.initialCount
    8
      tick: =>
    9
                                        @setState count: @state.count + 1
    10
      render: ->
    11
                                        div onClick: @tick,
    12
                                        'Clicks: '
    13
                                        @state.count
    Section 8

    Conventions for React DOM & JSX

    • React DOM elements are expected to be in camelCased.

    • the camelCasing of DOM matches what you would write for custom components: <Typeahead onClick=../> and <div onClick=.. />

    • These camelCased attributes are usually what you write when updating the DOM via JS (input.maxLength).

    • One current confusing exception is that class= is normalized automatically into className= at transform time.

    • Use className attribute instead of class

    • Use htmlFor attribute instead of for

    • Use <textarea value="something"> instead of <textarea>something</textarea>

    • Custom HTML attributes may be data-attr and all lower case.

    • Make use of ternary operators, wherever  required for example: React.render(<div id={condition ? 'msg' : ''}>Hello World!</div>, mountNode);

    Anti-pattern

    Props in getInitialState Is an Anti-Pattern:

    Instead of:

    9
    1
    var MessageBox = React.createClass({
    2
      getInitialState: function() {
    3
        return {nameWithQualifier: 'Mr. ' + this.props.name};
    4
      };
    5
      render: function() {
    6
        return <div>{this.state.nameWithQualifier}</div>;
    7
      }
    8
    });
    9
    React.render(<MessageBox name="Rogers"/>, mountNode);

    Try this:

    6
    1
    var MessageBox = React.createClass({
    2
      render: function() {
    3
        return <div>{'Mr. ' + this.props.name}</div>;
    4
      }
    5
    });
    6
    React.render(<MessageBox name="Rogers"/>, mountNode);

    Note: It won’t be an anti-pattern if we make it clear that synchronization's not the goal.

    Spread Operator in JSX:

    4
    1
      var props = {};
    2
      props.foo = x;
    3
      props.bar = y;
    4
      var component = <Component {...props} />;

    You can also use the spread operator (...) to override props:

    3
    1
      var props = { foo: 'default' };
    2
      var component = <Component {...props} foo={'override'} />;
    3
      console.log(component.props.foo); // 'override'

    The spread operator is already supported for arrays in ES6. There is also an ES7 proposal for Object Rest and Spread Properties.

    Section 9

    The Flux Application Architecture

    Flux plays a key role if your application use dynamic data.

    Don't try to compare Flux to Model View Controller (MVC) architecture, Flux is just a term to describe smart uni -directional data flow.


    Image title

    Figure 3: An Overview of Flux Architecture

    Keys ideas:

    • Views "Dispatch" "Actions".

    • "Store" Responds to Dispatched Events.

    •  Store Emits a "Change" Event.

    • View Responds to the "Change" Event

    Points to remember:

    • A "dispatcher" is essentially an event system.

    • There is at most one global dispatcher.

    • “Store” is specific collection of logic and data.

    • A “Store” is a singleton.

    • A store is not a model. A store containsmodels.

    •  A store is the only entity in the application that is aware of how to update data.

    • Only stores registers to dispatcher callbacks. store emits an event, but not using the dispatcher!

    • When store data changes, your views shouldn't care if things were added, deleted, or modified but just re-render.

    Section 10

    React v0.14

    React version 0.14 separated out all DOM related functionality into a separate dependency, which can be fetched from npm under the name `react-dom`

    React version 0.14 separated out all DOM related functionality into a separate dependency, which can be fetched from npm under the name `react-dom`

    Every new change in 0.14, including the major changes, is introduced with a runtime warning and will work as before until 0.15.

    The react package contains React.createElement, .createClass, .Component, .PropTypes, .Children, and the other helpers related to elements and component classes

    The react-dom package has ReactDOM.render, .unmountComponentAtNode, and .findDOMNode. In react-dom/server there is a server-side rendering support with ReactDOMServer.renderToString and .renderToStaticMarkup.

    So, if you wanted to duplicate the example Hello component from earlier with react v0.14, it would look like this:

    9
    1
    var React = require('react');
    2
    var ReactDOM = require('react-dom');
    3
    var Hello = React.createClass({
    4
    render: function() {
    5
    return <div>Hello World</div>;
    6
    }
    7
    });
    8
    ​
    9
    ReactDOM.render(<Hello/>, node);
    Section 11

    Testing Your Application With Jest

    Jest allows for painless JavaScript Unit Testing. It is built on top of the Jasmine test framework.

    Consider a scenario where you want to test the following div.js file:

    5
    1
    // sum.js
    2
    function div (value1, value2) {
    3
          return value1 /  value2;
    4
                     }
    5
                    module.exports = sum;
  • 1.    Create a directory __tests__/ with a file div-test.js
  • 8
    1
    // __tests__/sum-test.js
    2
    jest.dontMock('../sum');
    3
    describe('sum', function() {
    4
        it('divides 4 / 2 to equal 2', function() {
    5
            var sum = require('../div);
    6
            expect(div(4, 2)).toBe(2);
    7
         });
    8
    });

    2.    Run npm install jest-cli --save-dev

    3.    Add the following to your package.json

    1
    1
    { ... "scripts": { "test": "jest" } ... }

    4.    Run npm test

    1
    1
    [PASS] __tests__/sum-test.js (0.015s)

    Just follow the above steps, and you are ready to run with Jest!

    Note: For a react component, we follow the same steps along with it, we will have to use ‘React.addons.TestUtils`.

    Like This Refcard? Read More From DZone

    related article thumbnail

    DZone Article

    The Drawbacks of MobX
    related article thumbnail

    DZone Article

    The Cypress Edge: Next-Level Testing Strategies for React Developers
    related article thumbnail

    DZone Article

    Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
    related article thumbnail

    DZone Article

    Power BI Embedded Analytics — Part 1.1: Power BI Authoring Data Federation
    related refcard thumbnail

    Free DZone Refcard

    Getting Started With Low-Code Development
    related refcard thumbnail

    Free DZone Refcard

    JavaScript Test Automation Frameworks
    related refcard thumbnail

    Free DZone Refcard

    Salesforce Application Design
    related refcard thumbnail

    Free DZone Refcard

    E-Commerce Development Essentials

    ABOUT US

    • About DZone
    • Support and feedback
    • Community research
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Core Program
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 3343 Perimeter Hill Drive
    • Suite 100
    • Nashville, TN 37211
    • support@dzone.com

    Let's be friends: