React.js - the two minute intro

React.js is a javascript UI library which helps you build responsive, interactive user interfaces for your web-based applications.

In practice this means you'll write your markup and UI logic (to do things like showing/hiding elements when buttons clicked etc.) in javascript.

Now you don't have to use a library or framework; you could just bypass React and interact with the elements on your web site using plain old javascript.

var button = document.getElementById('sayHelloButton');

button.addEventListener('click', function(e){

    document.getElementById('greeting').innerHTML = 'Hello ' 
        + document.getElementById('name').value;

}, false);

But this has a few shortcomings.

  1. Your javascript code is dependent on "magic strings" to know which elements you're trying to work with (greeting and sayHelloButton in this case)

If you (or someone else) changes the id of your sayHelloButton in the HTML for your page your code is instantly broken.

  1. You end up writing a lot of imperative code to make changes to your UI.

The code above is imperative; we have to tell the browser step by step how to render our data (find this element, set its innerHTML to this concatenated string).

Imperative code can get pretty verbose pretty fast. You have to write (and read) a lot of lines of code to make sure your DOM elements are in the state you expect (hide this element, unhide that element etc.).

React.js takes a declarative approach...

nameChanged(e) {
    this.setState({name: e.target.value});
}

render(){
    return <div>
        <input type="text" onChange={this.nameChanged}/>
        <span>Hello {this.state.name}</span>
    </div>
}

Notice how we've done away with the button entirely in this scenario.

When the value of the text input changes, something called "state" in our React component is updated with the new value; React.js then takes care of updating the span element's innerHTML to reflect the new value.

This declarative approach, generally speaking, makes it easier to reason about our code and to understand what drives any particular part of our user interface.

Instead of reading many lines of code and trying to maintain a mental model of what state the UI might be in, you can simply figure it out by looking at the markup itself.

So, with those fundamentals in mind, let's have a go at building our first feature.

<< A brief overview of what we need