Skip to main content

Elements

React implements a browser-independent DOM system for performance and cross-browser compatibility. They call this the Virtual DOM.

React elements are the building blocks of React applications. An element describes what you want to see on the screen.

One might confuse elements with a more widely known concept of “components”. Typically, elements are not used directly, but get returned from components.

Part 1 - Hello World in JavaScript

In this part of the course we will create a Hello World application in vanilla JavaScript. We will later rewrite the application to use React.

  1. Create directory demos

    mkdir demos
    cd demos
  2. Open demos in your editor of choice

    If you are using VS Code you can type the following command on the command-line to open the editor

     code .
  3. Create file index.html

  4. Add the following code

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    </head>
    <body></body>
    </html>

    If your editor supports Emmet you can use the code snippet html:5

  5. Add a div element with an id of root

    <body>
    + <div id="root"></div>
    </body>

    If your editor supports Emmet you can use the code snippet div#root

  6. Add the following script tag to reference a JavaScript file that we will create in the next step.

    <body>
    <div id="root"></div>
    + <script type="text/javascript" src="/main.js"></script>
    </body>

    ! Be sure that the main.js script tag's src attribute starts with a / or the later router examples will not work properly when you refresh the page.

  7. Create a new file demos/main.js

  8. Add the following code to demos/main.js

    const rootElement = document.getElementById('root');

    const element = document.createElement('div');
    element.textContent = 'Hello World';
    element.className = 'container';
    rootElement.appendChild(element);
  9. Create a package.json file to store your local project dependencies. Open a command prompt/terminal in the demos directory and run the following command.

    npm init --yes

    --yes : tells npm says yes to accepting all the default values in the npm config file

  10. Install a web server

    npm install serve

    Assuming you would like to serve a static site, single page application or just a static file (no matter if on your device or on the local network), serve is a development web server that serves static content.

    It behaves exactly like static deployments on  https://vercel.com so it's perfect for developing your static project.

    For more information see: https://www.npmjs.com/package/serve

  11. Configure an npm script to start the web server

    // package.json
    {
    "name": "demos",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    + "start": "serve -s -p 5000"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
    "serve": "..."
    }
    }
  12. Run the web server

    npm start
  13. Open http://localhost:5000/ in your Chrome browser

14) Verify the page displays:

```
Hello World
```

Part 2 - Hello World in React

Hello World in JavaScript is not that different than it is in React. Let's update the code to see it in React.

  1. Open a new cmd prompt or terminal (leave serve running) and install React

    npm install react react-dom --save
  2. Add the script tags to include React on the page. Place them just below the root div but before the main.js script tag

    <script src="/node_modules/react/umd/react.development.js"></script>
    <script src="/node_modules/react-dom/umd/react-dom.development.js"></script>
  3. Update the code to use React

    const rootElement = document.getElementById('root');

    // const element = document.createElement('div');
    // element.textContent = 'Hello World';
    // element.className = 'container';
    // rootElement.appendChild(element);

    const element = React.createElement(
    'div',
    {
    className: 'container',
    },
    'Hello World'
    );

    ReactDOM.createRoot(rootElement).render(element);

The method signature for createElement is as follows:

React.createElement(type, [props], [...children]);
  1. Log out the React Element to the console.

    const element = React.createElement(
    'div',
    {
    className: 'container'
    },
    'Hello World'
    );

    + console.log(element);
    ReactDOM.createRoot(rootElement).render(element);
  2. Open Chrome DevTools (F12 or fn+F12 on a laptop) to see the console output.

    Notice that the React element is just an object with a props property that holds an object. And the props object has three properties we are using to represent the HTML element: type, children, and className.

  3. Instead of as the third parameter children (child elements-- even if just a text element as in this example) can be passed as part of the elements props (which is short for properties).

    const element = React.createElement(
    'div',
    {
    className: 'container'
    + children: 'Hello World'
    or
    + children: ['Hello World', 'Goodbye World']
    },
    - 'Hello World'
    );

    To summarize the React.createElement parameters are as follows.

    • Param 1: the element you want to create
    • Param 2: an object that contains all the properties you want to be applied or set on that element
    • Param 3: as a convenience, you can provide the children as any number of arguments after the props

React.createElement() performs a few checks to help you write bug-free code but essentially it creates an object like this:

// Note: this structure is simplified
const element = {
type: 'div',
props: {
className: 'container',
children: 'Hello World',
},
};

These objects are called React elements. You can think of them as descriptions of what you want to see on the screen. React reads these objects and uses them to construct the DOM and keep it up to date.


Reference