DEV Community

Cover image for Learning React (I): Three HelloWorld examples
David Rodríguez
David Rodríguez

Posted on • Edited on

Learning React (I): Three HelloWorld examples


Table of Contents

  1. Introduction.
  2. Hello World using a single HTML file.
  3. Hello World splitting files.
  4. Hello World building a local environment.
  5. Read More.

1. Introduction

React or React.js is one of the most popular resources for creation of Interfaces based in JavaScript, for SPA (Single Page Application), PWA (Progressive Web Application) or maybe “Isomorphic JavaScript” (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 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 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: The essential JavaScript library for building user interfaces.
  2. The basic React Dom Library: A package that provides DOM specific methods and resources.
  3. The Babel Tool: Babel is a compiler / transpiler that converts code to compatible versions. Also works with React and its native syntax, JSX. 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:

<!doctype html>
  <html>
     <head>
           <title>My custom title</title>
     </head>
      <body>
         <p>Hello World!</p>
      </body>  
  </html>
Enter fullscreen mode Exit fullscreen mode

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.

Remember: If you don't understand the above lines very well, it might be interesting for you to know the basics of HTML.

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:

<!-- 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>
Enter fullscreen mode Exit fullscreen mode

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:

<div id="root"></div>
Enter fullscreen mode Exit fullscreen mode

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:

<!-- 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>  
Enter fullscreen mode Exit fullscreen mode
  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:

<!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>
Enter fullscreen mode Exit fullscreen mode

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.

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, 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).

Configuring options in CodePen for creating React Examples.

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:

<div id="root"></div>
Enter fullscreen mode Exit fullscreen mode

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:

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 />);
Enter fullscreen mode Exit fullscreen mode

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:

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:

.button {
  padding: 40px;
  color: red;
  background: black;
}
Enter fullscreen mode Exit fullscreen mode

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.

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

$ sudo apt update
$ $ sudo apt upgrade -y
$ sudo apt install nodejs -y
Enter fullscreen mode Exit fullscreen mode

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 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.

$ sudo apt install npm
$ sudo n latest
Enter fullscreen mode Exit fullscreen mode

Updating nodejs with npm.

For updating npm as package manager, you can run:

$ sudo npm install -g npm
Enter fullscreen mode Exit fullscreen mode

This will install or just will update your current npm version and resources:

npm update with global flag.

Yarn 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.

$ 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 
Enter fullscreen mode Exit fullscreen mode

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:

$ sudo npm install -g create-react-app
Enter fullscreen mode Exit fullscreen mode

This command will install the package as a global resource with -g flag. This will do:

$ create-react-app --version
  5.0.1
Enter fullscreen mode Exit fullscreen mode

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:

$ npm uninstall -g create-react-app
[...]
$ yarn global remove create-react-app 
Enter fullscreen mode Exit fullscreen mode

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. npx is a package runner tool that comes with npm.

$ npx create-react-app hello-world
$ cd hello-world
$ npm start
Enter fullscreen mode Exit fullscreen mode

But you can use alternatives like npm or yarn:

$ 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
Enter fullscreen mode Exit fullscreen mode

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.

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.

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:

<p>Hello World! this is a React App from a local environment.</p>
Enter fullscreen mode Exit fullscreen mode

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.

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

Top comments (0)