Baby’s First Reaction

A “Hello, World” Example for React

Eric Elliott
May 28, 2015 · 8 min read

Getting Started With React

Baby’s First Steps

  1. Learn how to create a basic component. Let’s keep it really simple and just try to render “Hello, world!”, and optionally replace “world” with a different word.
  2. 1 & 2 are all you need to learn React, but that won’t help you build a real application. There’s no app without data. State (aka data) management deserves a big chunk of a book all to itself, so this article will just show you the absolute minimum you have to learn to get something to work.

Crawl Before You Walk

Is That HTML in My Milk?

You may be wondering how you get your webpage to actually render this component. First you need some HTML to load some script tags:

If you know some HTML, this should look pretty familiar for the most part.

Those `` script tags point to the React libraries on a popular JavaScript CDN (Content Delivery Network).

There are a couple of other interesting points to make. At the top of the body, there’s a `div` called `content`.

In the last script block, we call `React.render()` and pass your custom element as the first argument, and use the DOM API to tell React which DOM element will be React’s root node. React will render your components inside that node, and delegate all the UI events to it. A single event listener picks up all the event activity in React’s element tree and passes it into your event handlers.

That’s right. React has automatic event delegation. You don’t even have to think about it.

Since React needs to control its root node to function properly, it’s important that you don’t directly manipulate that root node with your JavaScript, and important that you don’t use the body tag as your root Node for React, because there’s a good chance that other JavaScript on the same page might conflict with React and cause strange bugs.

Using Variables

And of course we’ll need to make an adjustment to our `React.render()` call:


Jorge Elías — Hello (CC BY 2.0)

How Do You Interact?

For that to work, we’re going to need to maintain some state. React lets you keep state in components, but it’s usually a better idea to maintain state in an external store.

Are we going shopping!?

No, sorry. A store is just a place to store your state. To do that, we’re going to need to add a bit of meat to the main app.

React does not tell you how to handle state in your app. You may have heard of Flux. Flux is not part of React. It’s not even a library (though there are flux helper libs available). It’s an architecture.

There are lots of conflicting ideas about the right way to implement the Flux architecture, and lots of implementations are different enough that they’re only distantly related to Flux. Some people don’t use Flux at all. You might have also heard about Immutable.js and RxJS. This is a lot for a baby to process, so we’re going to save that discussion for another article.

It’s Playtime!

First we’ll remove the inline JS from the HTML and move that into a script called `app-client.js`:

Notice that since we don’t have the inline script anymore, we were able to remove the JSX transformer. We’ll compile the script with Babel so the JSX will already be transformed before it’s ever loaded into the browser. You should definitely do this before you make your app public.

Next we’ll update the JSX to make it interactive:

In the interactive JSX example we’ve added some things:


As you can see, we’re just checking a `mode` variable and showing or hiding the corresponding elements based on the value. I like to do it this way for a couple of reasons.

  1. Since React only updates the DOM that changed, keeping both views in the DOM will preserve the view state between renders.
  2. If you show & hide components with sub-components, there could be a performance benefit when you keep more of the markup in the DOM, because there will be less to change when React updates.

Event Listeners

In the example, we define a couple of event handlers. `onClick` is defined inline using the new ES6 arrow function syntax. Nice!

`onKeyUp` refers to a function of the same name. Let’s take a look:

As you can see, if the key pressed isn’t the “Enter” key, the function doesn’t do anything. Otherwise, we set the new word to the value of the form input field, and then change the mode back to “display”. Simple so far!

Let’s see what the whole `Hello` component looks like with these changes:

There are a few more things worth mentioning in this file:

  1. No `class`. You don’t need classes to create React components. Read the rest of the article to learn why I don’t use them.
  2. We’re exporting a factory instead of the component itself. In this example, it lets the caller pass in the `React` instance, which can avoid common problems with multiple instances of React on the same page. That can cause confusing errors. But it also allows you to add configuration options to your component later on, should you need to.
  3. `propTypes`. React lets you specify the types of your components properties. In debug mode, if you try to pass the wrong types to your components, you’ll get an error in your browser’s dev console. It also makes your component interface self-documenting, and could potentially help visual development tools that allow you to drag and drop components into app layouts.
  4. `.componentDidUpdate()` In addition to the `.render()` method, React also offers a variety of lifecycle hooks. In this case, we’re waiting until after the component has updated before we access the DOM and focus the input field. Any time you specify an element `ref` attribute, it will be added to `this.refs`.

TIP: Don’t try to access refs inside the render method. It will cause errors. You should access them in the lifecycle hooks that run after the DOM gets rendered.

This is all well and good, but how do our changes get handled by the app?

What I’m about to show you is just a placeholder. When you learn about Flux and stores or other React-friendly data models, you’ll want to use those instead. Here’s the source of our new `app-client` file:

There’s nothing fancy here. We require the `Hello` component, define the variables that hold our data, define some actions, and then call `React.render()` and pass in the props.

In this example, the action functions directly access the data, and directly call `render()`. This is just the simplest example I could think of to make this component work without explaining event emitters, reactive streams, library APIs and a bunch of little parts that a baby might choke on. You don’t want to do this in real apps. Speaking of which…

Watch Out for Bad Examples

If you look at the React documentation or google for examples, you’re going to be bombarded with examples of two different forms. The first, `React.createClass()` is (unofficially) deprecated. That means there’s a new and better way and `React.createClass()` is on its way out.

The second form you’re likely to see quite a lot of uses the ES6 `class` keyword. I don’t think that’s a good idea. Why avoid class?

Classes cause trouble,
and they’re an
awkward fit for React.

Why are Classes an Awkward Fit?

For now, trust me. Classes get you thinking the wrong way about the React architecture and ecosystem. Stick to stateless functions and composable components as much as you can, and you’ll be prepared for the future of React.

What are Stateless Functions?

When you use stateless functions and components, there’s no mess to trip on. In grown-up terms, holding onto state can cause bugs because different parts of your program might try to manipulate the same state in conflicting ways.

The Full Source

Hello, React!

Ren Kuo — p — (CC BY-SA 2.0)

Learn JavaScript app development
with Node, ES6 & React.

Preorder Now
for Lifetime Access to all
my JavaScript courses.

Eric Elliott is the author of “Programming JavaScript Applications” (O’Reilly), and “Learn JavaScript Isomorphic App Development with Node, ES6, & React”. He has contributed to software experiences for Adobe Systems, Zumba Fitness,The Wall Street Journal, ESPN, BBC, and top recording artists including Usher, Frank Ocean, Metallica, and many more.

He spends most of his time in the San Francisco Bay Area with the most beautiful woman in the world.

JavaScript Scene

JavaScript, software leadership, software development, and…

JavaScript Scene

JavaScript, software leadership, software development, and related technologies.

Eric Elliott

Written by

Make some magic. #JavaScript

JavaScript Scene

JavaScript, software leadership, software development, and related technologies.