The first steps in React JS for absolute beginners

Introduction

What is React?

So... you've heard about React, you know that a lot of cool stuff can be built with it, but do not know exactly what it is.

React (also known as React JS or React.js) is a JavaScript library developed by Facebook in 2011. There are a lot of JavaScript libraries today (jQuery, Parsley etc.) and React is one of them.

What exactly is a JavaScript library?

A JavaScript library is a collection of prewritten code snippets. These can be used to perform common JavaScript functions. JavaScript library code can be plugged into the rest of your project's code on an "as needed" basis. A JS library it's a different concept than a JS framework.

What is a JavaScript framework?

A JavaScript framework is a full toolset that help shape and organize your website or web application. To understand better the difference between a JS library and a JS framework let's think to a car. The pieces used to build a car (like the engine, wheels, seats etc.) which give the properties and functionality are the library. The whole template, blueprint which is used to build the car it's the framework. Some examples of JS frameworks: Node, Angular, Vue etc.

What can you do with React?

React helps developers to build user interfaces (UIs). In terms of websites and web applications, UIs are the collection of buttons, on-screen menus, search bars, and anything else someone interacts with to use a website or app.

Some preliminary thoughts

In order to start learning React, you need to know some HTML, some CSS and JavaScript. But don't worry, you do not need to be an expert! You will also need to know ES6 and JSX.

What is ES6?

Wait a minute... This sounds confusing, right? Yes.. probably, but ES6 is actually JavaScript.

ES6 is the shortname for ECMAScript 6. The JavaScript core language features are defined in the ECMA-262 standard. The language defined in this standard is called ECMAScript. What we know as JavaScript in browsers is actually a superset of ECMAScript. So we can think that ES6 is kind of a version of JavaScript. It was published in 2015 and since then it's been become supported by all major browers (Chrome, Firefox, IE, IE / Edge, Safari, Opera). There are a few other versions released, like ES7, ES8 and ES9 but, at the moment when I'm writing this article, they are not supported in all major browers.

ES6 brings a lot of cool new features to JavaScript (the ES5 version). These features vary widely from totally new objects and patterns to syntax changes and new methods on existing objects. The beautiful thing of ES6 is that all of its changes are oriented toward solving problems that developers encounter.

As an example, let's consider the arrow functions (also known as fat arrow functions) which ES6 brought to us. These arrow functions give a lot of clarity and code reduction to JavaScript.

Here's how we define a function in ES5:

ES5
function car (brand) {
 return 'My car is ' + brand
}

And please check a way in which we can define the above in ES6:

ES6
const car = (brand) => {
 return `My car is ${brand}`;
}

What is JSX?

JSX is the shortname for JavaScript XML and it allows us to write HTML in React. So it is actually an easy way to write and add HTML in React.

As an example, let's consider the below JavaScript code:

const myheading = React.createElement('h3', {}, 'This is not JSX!');

ReactDOM.render(myheading, document.getElementById('root'));

Now take a look to the below example which does the same thing as above, using JSX:

const myheading = <h3>This is JSX!</h3>;

ReactDOM.render(myheading, document.getElementById('root'));

So the above examples add that H3 heading on a page. As you can see, the JSX example uses less code.

Using Visual Studio Code as IDE

I recommend using [https://code.visualstudio.com/](Visual Studio Code) for your React projects. It's developed by Microsoft and it has versions for Mac, Windows and Linux. This IDE (integrated development environment) is really easy to use, it has lot of extensions which can be installed and it is FREE.

One thing I like about Visual Studio Code is that is has an integrated terminal, so I do not have to use the Windows one which it is not so cool.

If you are already using another IDE and you are happy with it, that is totally cool.

Install Node.js

First thing to do is to install Node.js on your computer. If it is already installed, just skip this section.

We will install Node.js on a Windows computer. The install process it's pretty similar for Mac.

Go to nodejs.org and download any of the packages (LTS or Current):

install nodejs

Then go ahead and install it from your computer just like you do with any program.

After all is installed we need to check if everything is fine and if Node.js is actually installed. In Windows 10 jut type cmd in the left bottom Search box and then click on "Command Prompt". The "Command Prompt" window will open. It does not matter the path, just write this:

node -v

You will be able to see the Node.js version installed on your computer (-v refers to the version).

node version

If an error comes up, you need to restart your computer.

First step to React: create-react-app

Now it's time to start building our react app. Open your Windows cmd or your Mac bash. React gives us the possibility to easily generate a boilerplate version of a React application. First we need to use npm (Node package manager) to install the create-react-app command line interface (CLI) globally (-g). For this you need to add the following to your cmd:

npm install -g create-react-app

Press Enter and wait till it is installed.

In Visual Studio Code just go to File > Open Folder and open a folder where you want your app to be created. I have created my folder and named it react-beginner.

visual code react folder

Once we are inside the folder, in Visual Studio Code, go to View > Terminal. This will open, at the bottom of the screen, the integrated terminal.

vsc terminal

We will add the React app boilderplate to the directory. You need to add the following:

create-react-app .

create react app

Press Enter and wait for everything to install.

Files and folders of the React boilerplate

After everything is installed, your folder will look like this:

react boilerplate structure

Let's examine what's in the app folder:

  1. node-modules - it's the folder where all Node.js packages are added locally inside your app folder. You will use the ones you will need in your app by calling an "import" statement. We'll get to that later.
  2. public - this folder contains: favicon.ico (the application favicon), index.html (it's a template for the main app file that gets served on the browser), logo192.png and logo512.png (React's logo), manifest.json (it's a web app manifest that describes your application, used for example by mobile phones, if a shortcut is added to the home screen; it's used to populate the web app's icons, colors, names, etc) and robots.txt.
  3. src - it's the folder where all your app files can be found. We'll get to this when we will begin to build a simple React app.
  4. .gitignore - this file specifies the files that Git should ignore. We will not use it in this React mini-course.
  5. package.json - this file lists the packages your project depends on along with their versions. This is a Node.js file and it is very important.
  6. README.md - it has just some info and commands you can use. Will discuss about this later.
  7. yarn.lock - Yarn is a package manager that replaces the existing workflow for the npm client or other package managers while remaining compatible with the npm registry. It has the same feature set as existing workflows while operating faster, more securely, and more reliably. In order to get consistent installs across machines, Yarn needs more information than the dependencies you configure in your package.json. Yarn needs to store exactly which versions of each dependency were installed. To do this, Yarn uses a yarn.lock file in the root of the project. If you do not have Yarn installed on your computer, just add the below to your terminal:
npm install -g yarn

How is actually a React app working?

Now that we know the structure of a React application, let's see how it is actually working:

react process explained

  1. React app files - in a React app we can have a lot of files, tens or even hundreds of files.
  2. Webpack + Babel - Babel is a translator which translates the ES6 code into ES5 that browser (front-end) or Node.js (back-end) understands. Babel is sometimes called a transpiler. So all React files are translated to ES5 by Babel. Webpack will bundle the React app files into a single file. You don't need to do anything regarding Webpack and Babel because they happen behind the scenes in this case.
  3. index.html + bundle.js - index.html it's the file which is visible when you access the React app in a browser. bundle.js it's the file which containes all the React app files.

Second step to React: npm start

Now that we have created the react boilerplate and we have discussed a little about the files, folders and how a React app is working, it's time to render the app in our browser.

We will build a simple React app and first of all, to keep things simple and clear, we will delete some of the boilerplate files.

Delete all files in public folder, except index.html. Then delete all files in src folder, except index.js file. To delete a file in Visual Studio Code just right click on it (in left sidebar) and click on Delete.

When you will build your future React apps it is not needed to do this, of course. But I'm doing this for this mini-course in order to keep things simple.

Our project will look like this:

react app start files

Click on index.js inside src folder and delete everything what is there, as we are going to start the app from scratch.

In order to start the development server and be able to see how our app is looking, you need to open the terminal and add this:

npm start

Wait for it and a browser window will open at address http://localhost:3000/. Of course, this will be just a blank page and we can start to build our app now.

Build your first React app

Open index.js inside src folder, which it is am empty file now, and first thing we need to do it to specify that we use React. So we need to import React from the node_modules folder. The first line of code will be this, which specifies that we use React:

/src/index.js
import React from 'react';

Then, we need to import something else, which is ReactDOM:

/src/index.js
import ReactDOM from 'react-dom';

In React we work with components which are actually pieces of code which are connected and work together. So let's build our first component:

/src/index.js
const App = () =>{
  return <h2>My first React component!</h2>
}

As you already know, the above is a ES6 fat arrow function which renders on screen that heading. And the return part is asctually JSX. Remember, it is something that looks like HTML, but it is actually JavaScript written as HTML as I have explained above.

Something really important regarding the return part is that you can always return just a single element. So you cannot have something like this:

const App = () =>{
  return <h2>My first React component!</h2><div>The best component</div>
}

The above code will not work and will generate an error. But if you enclose everything in a single element and add the paranthesis for the return, it will work:

const App = () => {
  return (
    <div>
    <h2>My first React component!</h2>
    <div>The best component</div>
    </div>
    )
}

Just in case that you want to add a class to one of the elements, we need to rememnber that even this looks like HTML, it is actually JavaScript. So adding a class like this will not work and will generate an error:

const App = () => {
  return (
    <div class="myReact">
    <h2>My first React component!</h2>
    <div>The best component</div>
    </div>
    )
}

Instead, you just need to use className and it will work:

const App = () => {
  return (
    <div className="myReact">
    <h2>My first React component!</h2>
    <div>The best component</div>
    </div>
    )
}

Let's get back to our app code. In order to render that heading on screen we need to add another line of code:

/src/index.js
ReactDOM.render(<App />,document.querySelector('#root'));

The above line of code tells ReactDOM to add the React App component to element having root as ID.

If you go to index.html inside public folder, you will notince that there is a <div> with root as ID:

/public/index.html
<div id="root"></div>

react root

That is where the App component will be rendered on the screen. Note that App is enclosed in a tag which means it is a component (<App />).

So, the final code for your first react app is this:

/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';


const App = () => {
    return <h2>My first React component!</h2>
  }

  ReactDOM.render(<App />,document.querySelector('#root'));

And when you go to http://localhost:3000/ in your browser, you will see this:

react app browser

Congratulations for your first react app!

The structure of a React app

In order to cover some very important React features, we will build a little more complex app.

This app will allow us to filter a list of books.

Before starting the work on your app, you need to spend some time and think about its structure.

The general rule for React is to break everything into little pieces, which are called components. This is actually really smart, because whenever something is not working right or you want to change something in your code, you can always go to the right place.

React will always have a "parent" component which will contain all the other components of the application. In our case, we can also have a header component where we will add a search form. Then we will have a component which will list all the books. And this component will actually contain the book component. Like in the below image:

So we are going to build such an app in order to explain how other important React features work. Of course, this will not cover everything what React has to offer, but for an absolute beginner mini-course it will be enough.

Build a React Books Filter App

First of all we will need to create a few files.

As I have said above, a React app is composed of components and each component has a file.

We will use the React app we have just created and expand it.

Go to Visual Studio Code and open react-beginner folder in case it is not opened yet. (File > Open Folder)

Then open Terminal ( View > Terminal), type npm start and press Enter. After it is compiled, you will see your app in the browser (http://localhost:3000/).

Right click on src folder( left sidebar in Visual Studio Code) and select "New Folder". We will create a components folder inside src folder which will contain all the other components of the application.

From the above image you can see that we have the "parent" component (which will be index.js inside src folder) and then we have header component, books list component and book component.

Let's create these inside components folder. (left click on components folder and select New File). The new components files will be: header.js, books_list.js and book_item.js.

Open index.js and delete what's inside the return and just add an empty <div> there. Your index.js will look like this:

/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
    return (

       <div>


         
       </div>

    )
    
  }

  ReactDOM.render(<App />,document.querySelector('#root'));

Open header.js - this is the first component which we will build and which we will add to index.js.

For all React files the first thing we need to is to bring React to the file, in other words to import React.

The first line of code will be:

import React from 'react';

We will need to import ReactDOM in this case (as we did for index.js) because this is used to render something on the root.

Then we will create a component:

/src/components/header.js
const Header = () => {
        return ( 
            <header>

            </header>
        )
}

At this point we need a way to connect the parent component (index.js) and the header component (header.js). And this is very important. When we create a component, in order to make it available for other component, we always export it.

So we need to add this:

/src/components/header.js
export default Header;

Header component is available for other components now. In order to be able to use it in index.js we need to import it. Just like we did with React.

/src/index.js
import Header from './components/header';

As you noticed, in this case we had to use the path to the component. It is not needed to add the .js extension in the path because react already knows that we refer to that file.

The two components are connected now. There is one little step though. You need to add it to the render.

/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
    return (

       <div>

       <Header />
         
       </div>

    )
    
  }

  ReactDOM.render(<App />,document.querySelector('#root'));

When you add a component, as you can see above (<Header />), it looks like a HTML element. We did the same the the App component, as you can see in the code (<App />). This is the way we add a component and React will always recognize this code as being a component.

Class based and functional components in React

It's important to discuss these concepts in React.

We have already created a functional component:

const Header = () => {
        return ( 
            <header>
              Something here
            </header>
        )
}

This is how it looks. It is a fat arrow function.

To build the same thing as a class based component we need to use the class keyword:

class Header extends React.Component {
      render() {
        return ( 
            <header>
              Something here
            </header>
        )
      }
}

You can notice that it is different that a functional component.

In order to connect this class to React, we use extends React.Component.

Whenever we use a class component, we need to use the render method.

For your apps, you can use functional or class based components as you like. There are no rules about this.

But I wanted to explain a little about these two components types in React because I wanted to say that functional components do not have a "state". Functional components in React are "stateless".

On the other side, whenever a class based component is created in React, it has a default "state".

I know what is the next question...

What is state in React?

State in React is an object which behaves like a database, like a "memory" or a "place" or "container". In this state we can store different values, we can check different events, we can control actually how the application behaves.

If it is not clear, let's check the below code:

class Header extends React.Component {

      state = {  
          color: 'red',
          engine: 'powerful'
      }

      render() {
        return ( 
            <header>
              {this.state.color}
            </header>
        )
      }
}

As you can see above, state is defined (state is a reserved keyword for React so whenever you use it it will refer to React's state) and we add color and engine properties to it (you can add anything you want there). This is how you define the state.

Then, inside render, you can see this: {this.state.color}. Whenever you see the curly braces used like this, it means that there we have dynamic data. If we want to show dynamic data in React, we need to use {}.

When the application is rendered we will see on the screen: red.

State looks like a normal object, so why is this so important? At a first look, we can achieve the same result with any other regular JS object.

The beauty, and the reason why state is one of the key concepts in React, is that whenever we change the state, React knows that we changed it and it rerenders the application. Not reloading the page, but just rerenders the render piece of code. Pretty cool, right?

How do we change the state? It's really easy. Again, React has a special method for this: setState.

Here's how can can change the state from our example:

this.setState ({
  color: 'green'
})

Of course, the above code, in a real application, will be added inside a function, or will trigger when a certain events happens etc. We will see that in our books application.

One thing related to the class components which use the state object is that they use more resources than functional components. But, as I said before, functional components do not have a state, they are stateless. So, at this point we need to discuss about another key concept in React: "props".

What are props in React?

When we create a component, not matter if it is a functional one or a class component, by default we have these "props". Props are used to transfer some data, some parameters between components.

To make things clear let's have a very simple example.

Let's say that in index.js we import a component from books_list.js called BooksList.

/src/index.js
    render(){
        return (
            <div>
                 <Header/>
                 <BooksList booksnumber="so many books">
                    <h1>
                        These are my books!
                    </h1>
                 </BooksList>
            </div>
        )
    }  

You noticed that booksnumber="so many books"? In this case booksnumber is one of the props of BooksList component. So this is actually something similar to a HTML attribute like for example src here: <img src="book_cover.jpg">.

But how do we send propos to the component? When the component is defined all you have to do is to add props as an argument:

/src/components/books_list.js
const BooksList = (props) =>{

    return (
        <div>
           
        </div>
    )
}

So you have captured those props? How do you print them on screen?

All you have to do is use curly braces + props."name of the props". Not clear? In our case it will look like this:

const BooksList = (props) =>{

    return (
        <div>
            {props.booksnumber}
        </div>
    )
}

The above code will print on screen this: so many books.

What are children props?

As you have noticed above, when we added the BooksList component code we have that <h1> tag. That is actually considered as children props (children is another reserved word).

const BooksList = (props) =>{

    return (
        <div>
            {props.children}
            {props.booksnumber}
        </div>
    )
}

In the above example, {props.children} will print this on screen: These are my books! (this will be, of course a h1 tag).

Finish our books application in React

Now that we know about import, export, functional and class components, state and props, let's begin our books app.

Before we start to build the code for index.js, we will create a JSON file which will contain the books info. We will name it books_db.json. A JSON file is a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format. We will add this file inside src folder.

/src/books_db.json
[

{
    "id": 1,
    "title": "Anna Karenina",
    "author": "Leo Tolstoy"
},
{
    "id": 2,
    "title": "The Great Gatsby",
    "author": "F. Scott Fitzgerald"
},
{
    "id": 3,
    "title": "In Search of Lost Time",
    "author": "Marcel Proust"
},
{
    "id": 4,
    "title": "Moby Dick",
    "author": "Herman Melville"
},
{
    "id": 5,
    "title": "One Hundred Years of Solitude",
    "author": "Gabriel Garcia Marquez"
}

]

Then we build the index.js file:

/src/index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import JSON from './books_db.json';

// app components
import Header from './components/header';
import BooksList from  './components/books_list';

class App extends Component {

    state = {
        books:JSON,
        selection:[]
    }

    getBook = (event) => {
        let bookTitle = event.target.value;
        let selection = this.state.books.filter((book)=>{
            return book.title.indexOf(bookTitle) > -1
        });
        this.setState({
         selection
        })
    }

    render(){
        let booksSelected = this.state.selection;
        let booksAll = this.state.books
        return (
            <div>
                 <Header bookTitle={this.getBook}/>
                 <BooksList books={booksSelected.length === 0 ? booksAll : booksSelected}>
                    <h3>The list of the books</h3>
                 </BooksList>
            </div>
        )
    }  
}

ReactDOM.render(<App/>,document.querySelector('#root'));

As you can see first we import JSON and also the other components.

Then we create the App class and add the state.

In the render part we have a Header component forst which will contain an input field where we will type the title of the book we want to select. This Header component uses a function (getBook) to "capture" the text we type. It uses state to update the text we type (selection) and also ES "filter" method is used.

Then we have the BooksList component which will list all the books.

Then we will create the books_list.js file:

/src/components/books_list.js
import React from 'react';
import BookItem from './book_item';

const BooksList = (props) =>{

    const books = props.books.map((book)=>{
        return(
            <BookItem key={book.id} book={book}/>
        )
    });

    return (
        <div>
            {props.children}
            {books}
        </div>
    )
}

export default BooksList;

As you can see above, we import BookItem component which we will build in the next file.

Then we use ES "map" method to go through all books which we capture with props ( which are actually those from index.js file - <BooksList books=... ).

The return part just shws the books.

The next file is book_item.js:

/src/components/book_item.js
import React from 'react';

const BookItem = ({book}) =>{

    return(
        <div>
            <h2>{book.title}</h2>
            <h3>{book.author}</h3>
        </div> 
    )
}

export default BookItem;

This actually lists books one by one.

The last file is header.js:

/src/components/header.js
import React from 'react';

const Header = (props) =>{
        return ( 
            <header>
                <div>BOOKS</div>
                <input 
                    type="text" 
                    onChange={props.bookTitle}
                />
            </header>
        )
}


export default Header;

Again, this gets the props from index.js file (<Header bookTitle=...).

Now, the applicatine is complete and when you type something in the header input will only show the books titles which match that word.

books app react

When you type a word it will show the correspondednt book:

react books app results

The application is loking very basic and you can add CSS in order to look better. It will be a good exercise for you.

I have included below the whole React application and you can download it.

DOWNLOAD REACT BOOKS APPLICATION

Don't forget to run npm install, because node_modules is not included in the above .zip.

Deploy your React application

When you are ready to deploy your Rect app you just need to add this to your Terminal:

npm run build

This will create the static files and we will use the Express server to serve those static files. But this will be the subject for a different article.

Conclusion

React is really complex and we only managed to cover a few very important things so far. We managed to build a nice app and I hope that this article helped you to understand the first steps in React.

Comments closed

Please contact me, if you have any questions or suggestions.