Baby’s First Reaction

A “Hello, World” Example for React

Getting Started With React

Let’s face it. Getting started with React is way harder than it should be. First you have to set up your environment (see “How to Use ES6 for Isomorphic JavaScript Apps”), then you have to figure out the right syntax to create a component, and then you have to figure out how to manage state. There’s a lot to learn before you can stop crawling and start running.

Baby’s First Steps

  1. Set up Babel — read “How to Use ES6 for Isomorphic JavaScript Apps”.
  2. 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.
  3. 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

The first thing you need to do is create a component. Here’s the simple example you’ve been looking for:

Is That HTML in My Milk?

That little bit of HTML there isn’t actually HTML. It’s JSX: a markup syntax that looks like HTML but acts like well written JavaScript. Read “JSX Looks Like an Abomination but it’s Good for You”. You’ll need Babel to transpile it for you. (Scroll back to Step 1).

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

“Hello, world!” is a great start, but it’s a little cliche. Let’s try something else. First we’ll make a template out of that component so we can fill in the { blanks }:

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?

Toys aren’t very interesting if you can’t play with them. Don’t worry, React has great features to handle user interaction. We talked a little about React’s event system in “JSX Looks Like an Abomination”. Let’s use some similar code to let you change who we’re saying hello to. When the user clicks on the word “puppy”, it will turn into an input field and let them type a replacement.

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!

Let’s get started on the interactive version.

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:


We need styles to control whether or not the user sees the edit mode, or the display mode. Let’s take a look at how we created those styles:

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

Looking back at the new JSX, you’ll notice that there are a couple of event listeners. Read “JSX Looks Like an Abomination but It’s Good For You” to learn about React’s automatic event delegation, and why this markup is a really great way to handle events.

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

You know that toddler who’s always throwing toys at people? You don’t want to follow that example. Unfortunately, the internet is flooded with bad examples you should try to avoid.

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?

React works best with immutable data structures and reactive streams — concepts borrowed from functional programming. Those are huge topics for a “Hello, world” post take on, so you can read about immutability and functional programming in other articles later.

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?

State is just a fancy word for data. A stateful function holds onto data. You might say it’s like leaving your toys scattered all over the floor. There’s a chance somebody could trip on them and get hurt.

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

Of course, I’ve posted the full React hello world example to GitHub. If you look at it closely, you’ll see some other neat things in the `package.json` and `.eslintrc` files. Enjoy.

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.