Reader small image

You're reading from  React.js Essentials

Product typeBook
Published inAug 2015
Reading LevelIntermediate
PublisherPackt
ISBN-139781783551620
Edition1st Edition
Languages
Right arrow
Author (1)
Artemij Fedosejev
Artemij Fedosejev
author image
Artemij Fedosejev

Artemij Fedosejev is a technical lead living in London, United Kingdom. He is a self-taught web developer who has been a web developer since the early 2000s. Artemij earned his BSc in computer science from University College Cork, Ireland. He participated in the IGNITE Graduate Business Innovation Programme, where he built and launched a website that received the Most Innovative Project award. Artemij has played a key role in creating frontend architecture using React.js and Flux for various websites. Artemij created a number of open source projects, including Snapkite Engine, Snapkite Stream Client, and other projects.
Read more about Artemij Fedosejev

Right arrow

Chapter 2. Create Your First React Element

As many of you know, creating a simple web application today involves writing the HTML, CSS, and JavaScript code. The reason we use three different technologies is because we want to separate three different concerns:

  • Content (HTML)

  • Styling (CSS)

  • Logic (JavaScript)

This separation works great for creating a web page because, traditionally, we had different people working on different parts of our web page: one person structured the content using HTML and styled it using CSS, and then another person implemented the dynamic behavior of various elements on that web page using JavaScript. It was a content-centric approach.

Today, we mostly don't think of a website as a collection of web pages anymore. Instead, we build web applications that might have only one web page, and that web page does not represent the layout for our content—it represents a container for our web application. Such a web application with a single web page is called (unsurprisingly...

Understanding the virtual DOM


Why do we need to manipulate the DOM in the first place? Because our web applications are not static. They have a state represented by the user interface (UI) that a web browser renders, and that state can be changed when an event occurs. What kind of events are we talking about? There are two types of events that we're interested in:

  • User events: When a user types, clicks, scrolls, resizes, and so on

  • Server events: When an application receives data or an error from a server, among others

What happens while handling these events? Usually, we update the data that our application depends on, and that data represents a state of our data model. In turn, when a state of our data model changes, we might want to reflect this change by updating a state of our UI. Looks like what we want is a way of syncing two different states: the UI state and the data model state. We want one to react to the changes in the other and vice versa. How can we achieve this?

One of the ways...

Installing React


To start using the React library, we need to first install it. I am going to show you two ways of doing this: the simplest one and the one using the npm install command.

The simplest way is to add the <script> tag to our ~/snapterest/build/index.html file:

  • For the development version of React, add the following command:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0-beta3/react.js"></script>
  • For the production version version of React, add the following command:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0-beta3/react.min.js"></script>

There is a difference between the two that we'll learn about in the later chapters of this book. For our project, we'll be using the development version of React.

At the time of writing, the latest version of React library is 0.14.0-beta3. Over time, React gets updated, so make sure you use the latest version that is available to you, unless it introduces breaking changes that are...

Creating React Elements with JavaScript


We'll start by familiarizing ourselves with a fundamental React terminology. It will help us build a clear picture of what the React library is made of. This terminology will most likely update over time, so keep an eye on the official documentation at http://facebook.github.io/react/docs/glossary.html.

Just like the DOM is a tree of nodes, React's virtual DOM is a tree of React nodes. One of the core types in React is called ReactNode. It's a building block for a virtual DOM, and it can be any one of these core types:

  • 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 represents textual content and it's a virtual representation of a Text Node in the DOM.

ReactElements and ReactTexts are ReactNodes. An array of ReactNodes is called a ReactFragment. You will see examples of all of these in this chapter.

Let's start with an example of...

Rendering React Elements


The ReactDOM.render() method takes three parameters: ReactElement, a regular DOMElement, and a callback function:

ReactDOM.render(ReactElement, DOMElement, callback);

ReactElement is a root element in the tree of ReactNodes that you've created. A regular DOMElement is a container DOM node for that tree. The callback is a function executed after the tree is rendered or updated. It's important to note that if this ReactElement was previously rendered to a parent DOM Element, then ReactDOM.render() will perform an update on the already rendered DOM tree and only mutate the DOM as it is necessary to reflect the latest version of the ReactElement. This is why a virtual DOM requires fewer DOM mutations.

So far, we've assumed that we're always creating our virtual DOM in a web browser. This is understandable because, after all, React is a user interface library, and all the user interfaces are rendered in a web browser. Can you think of a case when rendering a user interface...

Creating React Elements with JSX


When we build our virtual DOM by constantly calling the React.createElement() method, it becomes quite hard to visually translate these multiple function calls into a hierarchy of HTML tags. Don't forget that, even though we're working with a virtual DOM, we're still creating a structure layout for our content and user interface. Wouldn't it be great to be able to visualize that layout easily by simply looking at our React code?

JSX is an optional HTML-like syntax that allows us to create a virtual DOM tree without using the React.createElement() method.

Let's take a look at the previous example that we created without JSX:

var React = require('react');
var ReactDOM = require('react-dom');

var listItemElement1 = React.DOM.li({ className: 'item-1', key: 'item-1' }, 'Item 1');
var listItemElement2 = React.DOM.li({ className: 'item-2', key: 'item-2' }, 'Item 2');
var listItemElement3 = React.DOM.li({ className: 'item-3', key: 'item-3' }, 'Item 3');

var reactFragment...

Summary


We started this chapter by discussing the issues with single web page applications and how they can be addressed. Then, we learned what a virtual DOM is and how React allows us to build it. We also installed React and created our first React element using only JavaScript. Then, we also learned how to render React elements in a web browser and on a server. Finally, we looked at a simpler way of creating React elements with JSX.

In the next chapter, we'll dive deeper into the world of React components.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React.js Essentials
Published in: Aug 2015Publisher: PacktISBN-13: 9781783551620
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Artemij Fedosejev

Artemij Fedosejev is a technical lead living in London, United Kingdom. He is a self-taught web developer who has been a web developer since the early 2000s. Artemij earned his BSc in computer science from University College Cork, Ireland. He participated in the IGNITE Graduate Business Innovation Programme, where he built and launched a website that received the Most Innovative Project award. Artemij has played a key role in creating frontend architecture using React.js and Flux for various websites. Artemij created a number of open source projects, including Snapkite Engine, Snapkite Stream Client, and other projects.
Read more about Artemij Fedosejev