Complete Guide for 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.
Recommended :  5 Best JavaScript Frameworks for Mobile App Development

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 a ReactElement:

  1. Add the following code to your ~/snapterest/source/app.js file:
    var reactElement = React.createElement('h1');
    ReactDOM.render(reactElement, document.getElementById('react-application'));
  2. Now your app.js file should look exactly like this:
    var React = require('react');
    var ReactDOM = require('react-dom');
    var reactElement = React.createElement('h1');
    ReactDOM.render(reactElement, document.getElementById('react-application'));
  3. Navigate to the ~/snapterest/ directory and run Gulp’s default task:
    gulp
    

    You will see the following output:

    Starting 'default'...
    Finished 'default' after 1.73 s
    
  4. Navigate to the ~/snapterest/build/ directory, and open index.html in a web browser. You will see a blank web page. Open Developer Tools in your web browser and inspect the HTML markup for your blank web page. You should see this line, among others:
    <h1 data-reactid=".0"></h1>

    Well done! We’ve just created your first React element. Let’s see exactly how we did it.

    The entry point to the React library is the React object. This object has a method called createElement() that takes three parameters: type, props, and children:

    React.createElement(type, props, children);

    Let’s take a look at each parameter in more detail.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares