Learning React (I): Three HelloWorld examples
Tags: react, javascript, jsx
Published: 2022-05-03 18:23:36

---
title: Learning React (I): Three HelloWorld examples
published: true
description: How to build three different basic examples using React.
tags: react, javascript, reactjs, jsx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43l8ki1m8vp0c6y9jzf3.jpg
---

- Header Image from Unsplash, [user Markus Spiske, @markusspiske](https://unsplash.com/@markusspiske).  

--------------------------------------------
**Table of Contents**
1. [Introduction.](#1-introduction)
2. [Hello World using a single HTML file.](#2-hello-world-using-a-single-html-file)
3. [Hello World splitting files.](#3-hello-world-splitting-files)
4. [Hello World building a local environment.](#4-hello-world-building-a-local-environment)
5. [Read More.](#5-read-more)
<hr>



## **1. Introduction**   

**[React or React.js](https://reactjs.org/) is one of the most popular resources for creation of Interfaces based in JavaScript**, for [SPA (Single Page Application)](https://geekflare.com/single-page-applications/), [PWA (Progressive Web Application)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Introduction) or maybe [“Isomorphic JavaScript”](https://medium.com/airbnb-engineering/isomorphic-javascript-the-future-of-web-apps-10882b7a2ebc) (that is, the execution part in server and part in client). React was created by Facebook and Open-sourcered in 2013, [available since then from repositories](https://github.com/facebook/react) and libraries that can be fully integrated into your project.

In my case, I haven't used React until recently and due to the needs of a project: I'm working with [decoupled Drupal](https://www.acquia.com/resources/decoupled-drupal) models (headless) and the frontend had been created with React. I had used Angular for some pet-projects, so I had some basic SPA concepts already known. But now **I'm working with React and I wanted to share some basic steps** that can be executed to better understand some fundamental React concepts.  

I thought I'd put together some examples in a progressive way, from less to more, in a series of articles focused on working with React as a frontend technology on a daily basis. **So please, read, share and take advantage of everything you can find useful.**


## **2. Hello World using a single HTML file**    

Our first example is the most basic case that you can implement in your own environment without any configuration or package manager. **It only requires a single HTML file, a browser to open the HTML file and some external links to get the React resources**.  

**How does it work?** Well in order to create a new basic React example we only need some basic resources: 

1. [The basic React Library](https://reactjs.org/docs/getting-started.html): The essential JavaScript library for building user interfaces. 
2. [The basic React Dom Library](https://reactjs.org/docs/react-dom.html): A package that provides DOM specific methods and resources.
3. [The Babel Tool](https://babeljs.io/docs/en/index.html#jsx-and-react): Babel is a compiler / transpiler that converts code to compatible versions. Also works with React and [its native syntax, JSX](https://reactjs.org/docs/introducing-jsx.html). You write code in JSX and Babel will convert your code into usable JavaScript. That’s all. 


**Firstly**, we’ll create a new single and basic HTML file, called `react_hello_world.html` with an basic scheme of HTML tags inside, something like:  

```HTML
<!doctype html>
  <html>
     <head>
           <title>My custom title</title>
     </head>
      <body>
         <p>Hello World!</p>
      </body>  
  </html>
```

**Not difficult, right?** This kind of file can be created in your favorite text editor or in your selected IDE. And then you’ll only need to open the file with your browser and see the Hello World message in screen: 

![Hello World generated in a single HTML file.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7gnm17l8bzndzzu004h.png)


**Remember:** If you don't understand the above lines very well, it might be interesting for you to know [the basics of HTML](https://html.com/).  


**Secondly**, We’ll add the external React resources, by using the common HTML tag `<script>`. Doing so we’ll requesting all the necessary tooling: **React (basic)**, **React Dom (to operate with DOM in HTML)** and **Babel (the Compiler / Transpiler for JSX, the React syntax)**. We’ll include the new links in our `<body>` section:   

```HTML
<!-- Load React basic resources. -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
```

**Lastly**, We’ll create a new `<div>` tag which will be just like our new _“entry point”_ for the new React component: we’ll hook our custom element from this item, and we will call it “root” inside the `<body>` section as well:    

```HTML
<div id="root"></div>
```

And now we have to add the code of our new custom React Component, our salutation. We can see the next three parts in the snippet below:  

```HTML
<!-- Loading our new React component. -->
<script type="text/babel">
  <!-- 1- Description. -->
   class Greeting extends React.Component {
     render() {
  <!-- 2- Message to render. -->
       return (<p>This is a greeting generated from a unique               HTML local file!</p>);
     }
   }
  <!-- 3- Render Instructions. -->
  ReactDOM.render(
    <Greeting />,
      document.getElementById('root')
  );
</script>  
```

1. **The Description:** We’ve created a class extending React.Component.
2. **The Message to render:** We’ve added a string within a return function.
3. **The Render instructions:** We’ve used the ReactDOM library in order to launch the render of our new component/class, hooking the new item inside the `id=”root”` created `<div>` tag. 

Finally, our HTML file will look:  

```HTML
<!doctype html>
  <html>
     <head>
       <title>Document title</title>
     </head>
     <body>
       <p>Hello World!</p>
       <div id="root"></div>
       <!-- Load React. -->
       <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>

       <!-- Load our React component. -->
      <script type="text/babel">
         class Greeting extends React.Component {
           render() {
             return (<p>This is a greeting generated from a unique HTML local file!</p>);
         }
       }
    
       ReactDOM.render(
       <Greeting />,
       document.getElementById('root')
       );
     </script>  

    </body>  
</html>
```


We’ve already finished! We are done! **remember these three basic steps we have done (it will be the core of any basic development with React)**: we have created a class/component, we have asked it to render and we have indicated from which element of the DOM (HTML) we wanted to load the new component. **That's all!**  

And now if you open the file with your browser using right click from mouse or line command (you can use `$ xdg-open react_hello_world.html` ) you’ll see the new version of our Greetings file:   


![Hello World from an unique HTML file with React integration.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/epa9vpp5hpz2i39kwfc5.png)


## **3. Hello World splitting files**    

We have now created our first "Hello World" with React in a unified way, in a single file, loading the external resources and generating an output to a _"root"_ element. But this is not usually the daily reality, where we work with separate files of a different nature.   

To make this approach more "real", we are going to use a simple and intuitive platform that allows us to start separating resources. We will try with [CodePen.io](https://codepen.io), an online platform for testing code snippets especially focused on HTML / CSS / JavaScript for web.  

Enable an account and create a new snippet / pen. Then we only have to set some basic configurations in our new snippet / pen: **select Babel as JavaScript Preprocessor** (remember we’re using JSX syntax and It’s not pure JavaScript) and add external scripting for the basic `react` library and the `react-dom` library (as in the previous example).

* [https://unpkg.com/react/umd/react.development.js](https://unpkg.com/react/umd/react.development.js)
* [https://unpkg.com/react-dom/umd/react-dom.development.js](https://unpkg.com/react-dom/umd/react-dom.development.js) 


![Configuring options in CodePen for creating React Examples.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dchq5st210cxg6kyc37f.png)

CodePen will load the scripts in our code before rendering the snippet. **There we go**. 

**Firstly**, in the HTML tab we’ll include a basic original `<div>` working as _root_ element for our React example: 

```HTML
<div id="root"></div>
```

**Secondly**, we’ll build the JSX snippet in the JS tab. In this case, we’re using latest versions of React and as you can see, we have some differences with respect to the first example in this post. **Let’s see the code:** 

```javascript
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);

class Button extends React.Component {
  render() {
    return (<div className="button">Hello World! this is a greeting generated from different files.</div>);
 }
}
root.render(<Button />);
```

**What’s happening here?** Well, now we’re using `ReactDOM.createRoot`  instead of `ReactDOM.render` (as in the first case), due to changes in ReactDOM versions. This is something that has changed in the latest versions: `ReactDOM.render` is no longer supported in React 18, but I have kept the two different examples for different versions of React (15.x vs 18.x). You can read more info about it here: 

* [https://blog.saeloun.com/2021/07/15/react-18-adds-new-root-api.html](https://blog.saeloun.com/2021/07/15/react-18-adds-new-root-api.html)
* [https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html) 

**Finally**, we’ll add some (very basic) styles in order to see the rendering. We’ve add some colors to the specific `<div>` and the message in screen: 

```css
.button {
  padding: 40px;
  color: red;
  background: black;
}
```

The three tabs will load a React example using a Hello World message in our CodePen board, showing in console the internal structure:   

![Hello World message rendered from a Codepen board.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2crzxi193e32v862wq4.png)


## **4. Hello World building a local environment**  

Well, ok. We’ve built a first example using an unique HTML file, then we’ve built another Hello World example using separate files in an external environment (CodePen.io) and now we have to take another step: We are going to build a new example from a local environment, which involves the initial and basic installation and configuration of a local development environment for React. 

This is really the interesting part of this block: _What do we need to work locally with React?_ **Let's see**.



### Building up your local environment  

#### 1. Install Node.js (Ubuntu) 

   [Node.js](https://nodejs.org/en/) is an execution evironment for executing JavaScript from the server side. You will need to enable Node in your environment in order to work with React. In Ubuntu, you can install Node.js just by command line from the official repositories, by doing:   

```bash
$ sudo apt update
$ $ sudo apt upgrade -y
$ sudo apt install nodejs -y
```
But it can install an older version of Node.js… so we’ll need to execute an update..

#### 2. Install NPM // Update NPM (if needed) // Or install Yarn

We’ll need a package manager in order to resolve dependencies, so we can use [npm](https://github.com/npm/cli) and yarn (npm-compatible).  Using npm we’ll be able to update the current Node.js version to the latest stable version or non-stable. 

```bash
$ sudo apt install npm
$ sudo n latest
```

![Updating nodejs with npm.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3n3zwphfngclnirwtdi.png)


For updating npm as package manager, you can run: 

```bash
$ sudo npm install -g npm
```
This will install or just will update your current npm version and resources: 

![npm update with global flag.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bexbl5j8k8t74zlov8tj.png)

[Yarn](https://yarnpkg.com/) is another JavaScript package manager and is compatible with npm. It helps us automatize installing, updating, configuring, and removing npm packages, speeding up the installation process.  

```bash
$ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
$ echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
$ sudo apt install --no-install-recommends yarn

$ yarn --version
1.22.18 
```

#### 3. Install // Use create-react-app tool

Create React App is a very-comfortable tool for creating new apps based in React in your local environment. It works on macOS, Windows and Linux and you don’t need to install and configure resources as Babel or webpack: they are preconfigured! You’ll need to have Node >= 14.0.0 and npm >= 5.6 in your environment.

We can install create-react-app as a new dependency by using npm: 

```bash
$ sudo npm install -g create-react-app
```
This command will install the package as a global resource with `-g` flag. This will do: 
```bash
$ create-react-app --version
  5.0.1
```

And this will be ok and can be used for initial testing, **but its creators recommend us to uninstall the global resource in order to force that we’ll use the latest version of create-react-app per specific project**, just like a dependency. So use the next two versions: 

```bash
$ npm uninstall -g create-react-app
[...]
$ yarn global remove create-react-app 
```

### Creating the component  

Now we’re going to create our first Hello World React app in a local environment using scaffolding generated by the create-react-app package. And we’ll also use [npx](https://nodejs.dev/learn/the-npx-nodejs-package-runner). npx is a package runner tool that comes with npm. 

```bash
$ npx create-react-app hello-world
$ cd hello-world
$ npm start
```
But you can use alternatives like npm or yarn: 

```bash
$ npm init react-app hello-world-2
$ cd hello-world-2
$ npm start
[...] 
$ yarn create react-app hello-world-3
$ cd hello-world-3
$ yarn start
```

The fact is that after launching the start, the new application will be launched via the pre-configured web server and **the application will be deployed directly through port 3000** (be careful if you have it in use), opening from your favorite browser:

![Deploying in browser a new React app.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y223sclrcp2ubs6anugb.png)

Now we have a new React App created with scaffolding. **…But what do we have inside?**


### Inspecting the rendered component  

And at the end, we can open the just created folder with our new React App “Hello World” and see how the scaffolding provided by `create-react-app` is. Open now the created folder in your favorite IDE // Editor and see the content within the project:  

![React App basic resources from main folder.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/05tay5d2aj7pzf8rouj5.png)

Here you can see all the dependencies downloaded (folder “node_modules”), the public folder with all the resources for the web server, the `src` folder with the code of our app and other files like a basic gitignore (create-react-app starts git as control version system in the new folder) and the files for registering dependencies (`package-lock.json` and `package.json`). Among all these resources, there some important files that we’ve to review: 

1. **index.html**: The HTML main file, with a div called “root” as entrypoint for our app.
2. **App.js**: Our new component, described in JSX syntax and with a central message for screen.
3. **index.js**: The file loading the App component and charging the rendering from the root div present in index.html file. 

We’ll change the central message placed in App.js and we’ll put this: 
```HTML
<p>Hello World! this is a React App from a local environment.</p>
```

Now just saving the change and reloading the URL in browser you’ll see our custom updated message. **That's all!    We’ve done it!**

![Customizing message in the basic React App.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1bpikvukpx6jdzltfqko.png)

**To conclude**, we need to review all the little things we have practiced throughout this article on getting started with React. We wanted to create "Hello World" cases and almost without realizing it, we got a great snapshot (the big picture) of the fundamentals of React.

You can download the last two examples of this post from the [Github repository](https://github.com/davidjguru/react-examples): use the single HTML file and for the React local App, just run `$ npm install` (this will download all the node_modules folder for dependencies) and then `$ npm start` in order to run and launch the App in server + browser. 

**What do we know now?**

- The most basic resources for developing React App: The react library, the react-dom library and the Babel Transpiler (remember you’re using JSX syntax). 
- Basic resources for developing React code in a local   environment and how to install and use it:
 * Environment: Node.js
 * Package Managers: npm, yarn
 * Command Runner: npx
 * Package for basic React Apps: create-react-app
- Scaffolding of basic React Apps using create-react-app

## 5. Read More 

- [Basics of HTML](https://html.com/) 
- [HTML Basic Examples - WC3 Schools](https://www.w3schools.com/html/html_basic.asp) 
- [Getting Started with Create React App](https://github.com/facebook/create-react-app/blob/main/packages/cra-template/template/README.md)
- [Create React App - Quick Start](https://create-react-app.dev/docs/getting-started) 
- [Add React to a Website](https://reactjs.org/docs/add-react-to-a-website.html)