React, a gentle introduction.

Osmel Mora
React Ecosystem
Published in
6 min readMay 12, 2016

What is React?

React is a Javascript library for creating user interfaces, authored by Facebook and Instagram engineers. It’s aimed to solve the challenges involved when developing complex user interfaces with datasets that change over time, which is considered in the front-end development as the root of all evil.

What makes React different?

Using React you simply express how your app should look based on your data at any given point in time. When your data changes React handles automatically all the UI updates, saving you from imperatively manipulate the DOM. Which makes React very simple and declarative.

Since it’s not viable for performance reasons to actually trash and re-render the entire interface every time state data changes, React uses a fast, in-memory and lightweight representation of the DOM called virtual DOM. React basically uses a very optimized diff algorithm that compares the virtual DOM of the current and the previous state. The difference between them is what actually needs to be changed in the real DOM and React computes the most efficient DOM mutation for you.

React is all about components.

Components are the core of React and the view to your application. They are encapsulated and composable, you can mix and match them to build complex UIs favoring code reuse and separation of concerns.

React components are written in plain JavaScript, instead of template languages or the HTML directives traditionally used for web application UIs.

Data flow.

The other key point of React that makes it compelling is that implements one-way reactive data flow. This simplifies the mental model, it’s easier to reason about than traditional data binding, and makes your app more predictable.

Hello World please!!!

For getting started we will create the canonical Hello World example using React by undertaking the following steps:

  1. Create a new file and call it hello-world.html.
  2. Paste the following code in it:

3. Open hello-world.html in a browser and you should see something similar to the next image:

To get a clear picture of what’s going on we need to understand React’s building blocks and terminology. Just like the DOM is a tree of nodes, React’s virtual DOM is a tree of React nodes (ReactNode).

A ReactNode is a building block for a virtual DOM and can be either:

  • ReactElement: This is the primary type in React. It’s a light, stateless, immutable, virtual representation of a DOM element.
  • ReactText: This is a string or a number. It’s a virtual representation of a Text Node in the DOM.
  • ReactFragment: This is an array of ReactNode elements.

That being said, we can explain the example. The ReactDOM.render method takes three parameters: a ReactElement, a regular DOMElement, and a callback function:

ReactDOM.render(ReactElement, DOMElement, callback);

The ReactElement is the root element in the tree of ReactNodes that you have created, the regular DOMElement is a container DOM node for that tree, and the callback is an optional function executed after the tree is rendered or updated, is not used in the example.

The React object is the entry point to the React library. As you may notice it has a method createElement that creates a ReactElement and takes three parameters: type, props and children:

React.createElement(type, props, children);

Let’s take a closer look at each parameter.

The type parameter.

The type parameter can be either:

  • String: could be an HTML tag name such as div, p, span, and so on. React support all the common HTML tags and attributes.
  • ReactClass: is created via React.createClass method, basically a custom component.

In our example we are rendering a h1 tag, we also can achieve the same result using the built-in factories provided by the React.DOM object:

React.DOM.h1(null, 'Hello, World!!!')

To see a full list of the factories provided, open the console on your browser in the tab that you have the example opened and type:

Object.keys(React.DOM)

Press Enter and you’ll find something like this:

The props parameter.

The props parameter is a plain Javascript object. While creating DOM elements with React the props object represents the HTML attributes such as class and style. For example if you want to create a h1 tag with the class “title” and some style rules you’ll probably come up with something like this:

React.createElement(
'h1',
{
class: 'title',
style: 'background: red, color: white, font-family: Verdana'
},
'Hello, World!!!'
);

But this doesn’t work. First of all in the case of the class attribute, it matches a reserved keyword in Javascript, then you have to replace it with className. This also applies to the for attribute, instead you need to replaced with htmlFor.

When it comes to the style attribute you can’t use a string as you could normally do in plain HTML , instead you need a Javascript object and use the Javascript API names when dealing with CSS properties. Avoiding strings always reduces the risks of XSS attacks.

Let’s see an example that works:

React.createElement(
'h1',
{
className: 'title',
style: {
background: 'red',
color: 'white',
fontFamily: 'Verdana'
}
},
'Hello, World!!!'
);

The children parameter.

The children parameter describes what child elements this element should have, if any. A child element could be any ReactNode: a ReactElement, a ReactText or a ReactFragment.

In the hello-world.html example the children we pass in the React.createElement function is a ReactText withHello, World!!!”.

Now let’s see a more complex example.

Notice that in the li elements we are providing a special attribute named key that is a requirement for each child in an array or iterator and must be unique in its context.

We can also simplify it a little bit using built-in factories and other tricks.

But imagine a more complex HTML hierarchy and quickly become quite hard to translate it to React code and a nightmare to maintain. How can we simplify this problem?

Meet the controversial JSX.

JSX is an optional HTML-like syntax that allows us to create a virtual DOM tree and gets transpiled to JavaScript, it evaluates to ReactElements. JSX tags support the XML self close syntax so you can leave the closing tag off.

The previous example using JSX could be written like this:

As you can see, JSX allows us to write HTML-lish syntax in our Javascript code, it is not a template system, one of React’s core philosophies is that components are the right way to separate concerns rather than “templates” and “display logic”. The reasoning behind this is that markup and the code that generates it are tightly coupled, also display logic is usually very complex and using template languages to express it becomes cumbersome.

With JSX we can see more clear what our HTML layout will look like once it’s rendered. But this flexibility comes with a price, it needs an extra transformation step, in this case we are using the browser version of the popular Javascript transpiler Babel. In a real application this is not recommended, you should probably use a module bundler like Webpack and use the Babel loader.

Conclusions

React challenges conventions that have become the de-facto standards for Javascript frameworks best practices. Learning React implies a shift of mentality, on how we think of front-end development. React really hits on the status quo of what it takes to create maintainable user interfaces.

This is just a little bite of what React can offer you, and I hope you find it useful. In my next post I will cover React components. Don’t miss it!!!

--

--