by Matt Brennan

A Crash Course in React

This is React 101. I’m not going to cover modules, or build systems, or boilerplates, or ES2015, or hot loading, or any of that crap you don’t care about right now. Right now, you’re looking at a React app and thinking “okay, but what is it actually doing?”. We’ll start small. I’ll assume you can read Javascript.

Getting set up

Start with this JSBin. It includes everything you need to run React. Edit the code in the JSX (React) pane and see what happens in the Output pane. You can copy and paste the examples as you follow the post.

If nothing happens in the Output pane, wait a few seconds and click “Run with JS”. If you run into a problem and it doesn’t do what you expect, have a look at the Console pane (you can enable it with the buttons at the top) and see if there are any errors.

React as writing HTML in Javascript

At its most basic, React is a way of embedding HTML elements into Javascript and writing them to the page. That’s what’s going on in the JSBin I just gave:

ReactDOM.render(
  <h1>It works</h1>,
  document.querySelector('main')
);

So, we create an element (<h1>It works</h1>), and tell React to write it (ReactDOM.render) to the <main> element (document.querySelector('main')). If you’re unfamiliar with document.querySelector, all you need to know here is it finds (“selects”) the first tag named main.

You’ll notice in the Output pane it’s done exactly what I described. Try playing around with the HTML: any tag will work, and attributes as well. Try replacing the <h1> with a link (<a href="http://blog.153.io">cool blog</a>).

This “HTML-in-Javascript” syntax might seem a little ununsual. It’s not part of the base Javascript language but part of an extension to Javascript called JSX. It’s an alternative syntax for certain function calls: the above example is equivalent to React.createElement('h1', {}, ['It works'])1. You don’t need to write JSX to use React, but I find the syntax nicer, and it’s good to see exactly what HTML you’ll be creating when React renders it.

React as a templating language

JSX isn’t just HTML. It also supports variable interpolation, using {curly braces}:

var oneFiveThree = 153;

ReactDOM.render(
  <h1>my favourite number is {oneFiveThree}</h1>,
  document.querySelector('main')
);

Give that a go in the JSBin. You’ll see that the output has the number in the rendered HTML.

With other template languages, you can pass variables from outside the template so they can be reused. You can do something similar in React, but it works a little differently. React lets us think of HTML like it’s an thing within Javascript itself, just like numbers, strings and objects. So you can, for example, return an element from a function. That way we can write reusable templates, and pass in different values when we want to render something differently.

React calls functions that return HTML “Components”. And here’s where a lot of the power of React comes in: Components can be used just like HTML elements. When a tag’s name is all lowercase, it’s used as an ordinary HTML element. But when the tag name starts with a uppercase letter, it looks for a component instead. The attributes you give the tag are collected into an object and passed as the only argument to the function. We call these properties (or props for short). Let’s see an example:

function Favourite(properties) {
  return <h1>my favourite number is {properties.number}</h1>;
}

ReactDOM.render(
  <Favourite number="153" />,
  document.querySelector('main')
);

Paste that into JSBin, and you’ll (hopefully!) see exactly the same thing as the last example.

So how does React find your Components? It doesn’t! Remember that JSX becomes calls to React.createElement. With elements, the tag’s name is passed into createElement as a string. But with Components, it’s the reference to the function that’s passed in. So, any function that’s in scope when you write the tag can be used. Our example becomes React.createElement(Foo, {number: "153"}, []).

React as DOM updater

What happens if you change your mind about your favourite number? More generally, what if we call render again, but with something different? Well, it does exactly what you expect, although it’s a bit more subtle. First, have a look at this example:

function Favourite(properties) {
  return <h1>my favourite number is {properties.number}</h1>;
}

ReactDOM.render(
  <Favourite number="153" />,
  document.querySelector('main')
);

setTimeout(function() {
  ReactDOM.render(
    <Favourite number="256" />,
    document.querySelector('main')
  );
}, 5000);

Five seconds after you run it, the number changes to 256. Magic! But it’s even more magic than it appears: React only updates the parts of the DOM that change. So, in this example, only the text that’s part of the number will change. This keeps down the number of changes the browser itself needs to make, which can be performance-heavy. But more importantly, it makes it easier to reason about the state of your Components. You know that if something updates on the page if and only if its data or structure has changed.

This is a really important and powerful part of React. Conceptually, it lets you design you Components around “this is what I want to see in the browser at this moment”.

React as UI library

So far we’ve seen that React efficiently handles top-down changes to a page. We’ve not seen how to update just a single Component in-place. You’re unlikely to want to make all changes to all of your data in a single place; I prefer to let each Component handle its own data.

There’s another kind of Component we can use for this. They’re called Stateful Components2, and they can be used in exactly the same way as other Components and elements. They’re called Stateful because they contain an object called state. When the state changes, the Component is re-rendered.

We define these as classes using React.createClass. If you’re not used to classes from other languages, all we need to think of them as here is objects that contain multiple functions. The functions are part of the class and can’t be called from outside it. Inside the functions, we can refer to the object with the special variable this, and if the class has a function named render, you call it using this.render.

React’s classes have only one required function, render. It’s more or less the same thing as an entire ordinary Component, with the difference that the Component’s properties aren’t passed as the argument to render but are available as this.props. A class with just the render function is pretty much equivalent to an ordinary component.

I’ve been talking for a while now, so here’s an example:

function Favourite(properties) {
  return <h1>my favourite number is {properties.number}</h1>;
}

var Increment = React.createClass({
  getInitialState: function() {
    return {
      number: 153
    };
  },

  render: function() {
    return <div>
      <Favourite number={this.state.number} />
      <button onClick={this.clickButton}>+</button>
    </div>;
  },

  clickButton: function() {
    this.setState({number: this.state.number + 1});
  }
});

ReactDOM.render(
  <Increment />,
  document.querySelector('main')
);

Click the button. Your favourite number just went up! Let’s break the example down:

  getInitialState: function() {
    return {
      number: 153
    };
  },

getInitialState is the function React calls internally when creating your Component. The object you return will be the starting value of this.state.

  render: function() {
    return <div>
      <Favourite number={this.state.number} />
      <button onClick={this.clickButton}>+</button>
    </div>;
  },

The render function we mentioned before. When this.state updates, it’s called again, and the HTML it returns is updated in place. Again: React updates your Component in place, no matter where in the page it is. Unless you explicitly pass data between them, Components are isolated and can update themselves without changing the rest of the page.

So, we could modify this example to have two instances of <Increment>. If we did, each one would update separately as you click the button. But then you’d have two favourite numbers, and that’d be weird.

You might be wondering about the onClick={this.clickButton} part. It looks very similar to HTML’s own event attributes, and they are pretty much the same thing, with a a crucial difference. Notice the curly braces instead of quotes. That’s variable interpolation, so we’re sending React a reference to our actual clickButton function. With HTML’s attributes, you have to be able to reference a function globally, which won’t do here because we want a class function.

One last thing: render must return a single element. There’s no way to return multiple, so here I’ve wrapped them in a <div>.

  clickButton: function() {
    this.setState({number: this.state.number + 1});
  }

This is the function we’ve told React to call when the button is clicked. It calls this.setState to update the state. Why can’t we just do, say, this.state.number += 1? Without giving React a clue, it has no idea when we’ve updated the state. Calling setState tells React we’re updating the state, so it knows it needs to re-render the component.

All change please

This concludes our whistle-stop tour of React’s fundamentals. What’s next? The React website has some great resources for in-depth learning. I’d recommend downloading the Starter Pack and playing around with the examples. There’s also Thinking In React, which really helps you get to grips with how to structure your Components. Also have a good pore through the full documentation. There’s a lot of minutae about the Component API I haven’t covered but you’re likely to need for any real-world usage.

I hope you’ve enjoyed this guide, and I look forward to seeing what you build with React.


1 what’s that empty object? It’s the tag’s attributes. This tag doesn’t have any, so that’s why it’s empty. ↩︎

2 the React docs call these Components and simple functions “Functional Components” or “Stateless Components”. I prefer this naming as it makes it clear that state is something you’re adding to the Component. ↩︎