React JS Tutorials

React.js is a JavaScript library that emerged from recent JavaScript paradigm shift: replacement of multi-page website with single-page application design. This site was made for traditional JavaScript programmers as well as complete novice to the craft. This React tutorial site was designed to help you save a trip to a book store and get started quickly.

React Elements

In JavaScript almost everything is an object. Likewise in React everything is a React Element. React Elements are the building blocks of a React program. If you're writing one from scratch, the first thing you'll be doing is creating a React Element.

If you prefer video tutorials I created this React Elements Tutorial on YouTube. It's running length is just 6m:12s and it's pretty much the same (actually a bit less) of what you'll read here on this page.

But be careful, React Elements can manifest themselves in different ways. First and foremost as ReactElements created using React.createElement function, but also as JavaScript functions, objects, React Components and JSX statements. Which makes them sort of like a wolf in sheep's clothing. In this tutorial however we'll start simple. So don't worry about all those things yet!

A React Element is an abstract mental model of an HTML element, that can be represented by multiple JavaScript data types. This data-type transcendental nature of React Elements is the key feature of understanding React programming.

What Is A React Element?

When writing HTML, you enter tag names, attributes and their content (innerHTML). But React helps you do that in JavaScript. In fact, some React code is comprised of HTML tags typed directly as JavaScript statements using babel JSX transpiler.

We'll get to that in a bit, but for now think of React Elements as "programmatically created" HTML tags, doing which makes working with them much more efficient, directly from your JavaScript program!

Why in the world would you want to create HTML in JavaScript? At first, it might seem rather bizarre. But bear with this React Element tutorial. Only by observing practical examples will you see the full glory of React Elements.

Creating React Elements

The basic idea when creating a React Element, is to provide its HTML tag name, tag attributes in JSON format (that is, using curly brackets), and provide tag contents: the value of innerHTML of the tag being created.

React has a method createElement for that stemming from main React object. This example assumes you did include React library to your webpage.

If you did, the following is the method definition and its three arguments that should be used for creating new React elements:


  React.createElement(ElementName,        // "p", "div", "span", and so on...
                      ElementAttributes,  // { attr1: "value", ... }
                      ElementContent);    // "Text, or other HTML."
                      

Let's start with the most basic example of creating a React Element. We'll simply create a React Element here using native createElement method:


  var P = React.createElement("p",
                             { className: "paragraph" },
                               "Hello from React."
                             });
                             

This is exact equivalent of <p class = "paragraph">Hello from React.</p> in HTML. It's like a copy of a DOM element node, now at our command in JavaScript.

We have just created an HTML paragraph element that, in HTML, you'd otherwise create with the paragraph <p> tag. Except now, it is assigned to JavaScript variable P. It's almost like we returned an HTML element and stored it in variable P. But it is not shown on the screen yet, because it isn't mounted to DOM. Let's do that now:


  ReactDOM.render(P,
                  document.getElementById("root"), // render target
                  () => {
                      console.log("We've just rendered this paragraph."); });

The ReactDOM's render method "mounts" the P element we created to DOM. When mounting is finished, which is very fast, it means the P element we created earlier is now displayed on the screen.

Notice here the second argument is the target element into which P will be rendered into. React can render on the screen, but also to a file or some other "render target." Here we're dealing with basic UI applications, so our render target is another HTML element.

The () => { } is JavaScript "arrow function" (added since EcmaScript 6). It is just an anonymous callback function. It is executed when mounting process is finished.

What Is Mounting?

React has its own DOM called Virtual DOM. When you create elements, they are created on that virtual DOM. Mounting is just a fancy term for "attaching" elements (or later, React Components) to the actual DOM of your webpage (which is different from React's DOM.) So why does it have to be done this way?

In HTML, you simply add HTML tags or delete them by hand. In React, you mount and unmount elements from and to your web page's DOM, and you have not only control over the process but also responsibility to do so.

Remember that HTML web page requires you to create absolutely all HTML elements your page consists of regardless whether they will ever be actually shown on the screen, or not. The reason React "mounts" and "unmounts" elements, is so that unnecessary elements won't have to be rendered in the browser at all, if we don't want to or don't need to render them.

It's up to you as React programmer to decide when that is so. Making these logical decisions will help you write a much more efficient and lightning-fast React web applications! It just gives you a bit more control over what's rendered in the browser.

This saves memory, and makes React applications much faster than ones designed using the traditional HTML and JavaScript approach.

Creating React Elements Using JSX

Don't be puzzled if you see few different ways of creating a React Element. This is intentional. React provides different ways of creating (or thinking of) react elements. And you're going to have to adapt to thinking this way. This is probably the hardest habit to develop coming from traditional JavaScript background. But it is necessary.

One of them is using the aid of JSX library, which comes with babel. If you already added React to your webpage, as shown in this tutorial you can start using JSX "out of the box" without any additional development environment setup.

Working with React by simply adding React and ReactDOM libraries in <SCRIPT> a good way to get started quick, practice and experiment with React just to see how it works without additional setup. However soon as babel library is included, even though it will "still work" you'll feel a noticeable performance loss. It should only be used this way for small projects while learning React and testing code.

To set up React properly for professional web development, you have to install Node and run your React app as a server. (More about this later on this site, until then this YouTube tutorial I recorded should help you properly set up your local development environment.)

Anyways, let's create some React Elements using JSX now, shall we? And I'll also show you one small limitation of JSX along the way.


    // With JSX you simply type your HTML tag as a JavaScript statement:
    var P = <p className = "paragraph">Hello <i>there</i> from JSX.</p>;
    

Wait, what did just happen? We typed HTML directly into our JavaScript statement! And then assigned it as a "result" to P variable. We even nested the italics tag <i> inside, <p> and it did not generate a JavaScript error.

This JavaScript statement might look absurd at first. However, it isn't. In fact, we just created a copy of what we earlier created with React.createElement function. It's an exact equivalent. We just used JSX syntax that looks cleaner and much more elegant. The newly created element can be used in the very same way as any regular React Element. If you interchange the two, there will be no impact on your React application whatsoever. The two are identical.

JSX has one limitation. You cannot use "style" attribute within elements created in it. This is in part due to the fact that JSX is not HTML, it is more like XML, which makes attribute usage illegal. Here is the example of the erroneous usage of the style tag in JSX:


    // Error: cannot use "style" attribute in JSX.
    var P = <p className = "name">
        Hello
            <i style = 'color: orangered;'>
                there
            </i> from JSX.
        </p>;

Note that it's perfectly legal to span a JSX across multiple line breaks and format them just like HTML. This is acceptable and you actually want to do this in your React applications.

The error is accredited to the usage of style attribute inside JSX. That's forbidden.

To repudiate this problem React provides the ability to specify element style attributes using a JavaScript object.

Rendering (Or "Mounting") React Elements To DOM So They Can Be Displayed On The Webpage

This should be reiterated here. Once you create a React Element it is not shown anywhere on the screen. It resides in special Virtual DOM. To send (or "mount") it to the actual JavaScript DOM, so it shows up on your page, you have to call render method on it.

React's virtual DOM object is ReactDOM. So, by calling ReactDOM(element).render you will successfully mount your React Element.

Make a Donation

To support this site you can submit a donation to support these free tutorial articles that resemble book chapters. Tons of hard work goes into creating something like this, and your support helps run this website and continue serving useful educational material for JavaScript and React.js programmers.

© 2017 Copyright React JS Tutorials (reactjstutorial.net)

All content and graphics on this website are the property of reactjstutorial.net - please provide a back link when referencing on other sites.