header-banner-image
March 04, 2018 11:00

React guide for beginners

in: Tutorials
by: Meitar Bruner

Anyone who is currently engaged in the world of web development must have heard of React and the benefits of developing with this library. In this tutorial I will try to provide the basic tools that will allow any developer who has never touched the library to write his first React application.

It should be noted that this guide is intended for developers who already know the world of web development at least at the basic level, in order to start writing code in React according to accepted standards. The reader of this tutorial must have basic knowledge of Javascript and of course HTML and CSS.

Important Note: As a web developer, this guide may feel very long to build something very simple. I recommend finishing the guide to the end in order to understand the benefits that React provides in building web components that are reusable (can be used again and again between projects) and modular, so they are completely independent of each other.

 

 

What is the React library?

React is a JavaScript code library developed and maintained by Facebook to create user interfaces for browsers in an easy and efficient way.

 

 

How React Works?

First we will explain on the most basic cornerstone in the React - the Component. The library supports the creation of code snippets in Javascript that represent components in the app with specific behavior.

The JavaScript code for each component is independent of the rest of the other components in the application and has a "life cycle". We will expand on the life cycle immediately but first we will jump to the example of a code of such a component:

 

 

You may be reading this guide, certain that you know JavaScript but you do not understand anything that is written here. Do not worry, this code is not Javascript that most browsers can read. It is written in Node.js in combination with a special syntax called JSX (on both I will explain later).

First, Node.js is a Javascript language developed primarily for use in server side of applications and websites. This language runs on the operating system on your computer by the V8 engine - the same engine that runs your JavaScript code in the popular Chrome browser.

 

 

So why do we actually use it if it is not suitable for browsers?

Node.js has many advantages in code writing, which we will see later. With additional tools such as Webpack and Babel libraries, you can take advantage of programming in Node.js and make the Node.js code a Javascript code that different browsers can read.

JSX is a syntax that combines the familiar HTML elements. Notice that in the above image the render function returns an HTML element. This will make it easier for us because in React each component decides at any given time which elements of HTML to insert into the Document Object Model (DOM).

 

 

Install the workspace

Since this guide deals especially with quick entrance to coding in React, we use create-react-app. This is a "ready software" Facebook created to wrap all the various tools mentioned above, such as Babel - the part responsible for converting the code into code the browser knows how to read, and Webpack - which can take different files of code with dependencies between them and integrate them into the code that the browser knows how to read.

First, if you do not have Node.js on your computer together with NPM (Node Package manager), download and install it from here. NPM is a program installed on your computer and helps manage different packages of code written in Node.js - both on your operating system and in any project you write.

After NPM is installed on your computer, open the cmd (or terminal) and run the command:

npm install create-react-app -g

Now NPM will install the create-react-app on your computer.

After the installation finishes, run the command:

create-react-app my-first-app

Now the program will create a folder called my-first-app and install everything you need in order to write your first application on React. When the installation is complete, run the following commands:

cd my-first-app

npm start

After a few seconds, a browser will open at localhost:3000 on which we will do all the work. What you will see on the screen is:

 

תמונה 1: דף ברירת המחדל ש  create-react-app מציג

 

Enter the folder created by the create-react-app (my-first-app) and edit the src/App.js file.

We delete all content from the top div in the hierarchy, from the element that the render function returns, and insert the <h1>Hello World</h1> line instead. We also delete the import lines except the first line which loads React. We will save the file. Our code should look like this:

 

 

Note that saving the file will refresh the page in localhost:3000 and we will immediately see the changes on your browser screen thanks to the webpack created by us in the workspace.

We should see a white page with the words "Hello World" as in the picture:

 

תמונה 2: מה שיוצג בדפדפן לאחר עריכת App.js

Greetings! You've just wrote your first Hello World in React.

 

A little about what happens in this code:

import – Feature of Node.js to load code from other files. We will currently not elaborate on this function, but note that it exists only in the more advanced Node.js syntax, called EcmaScript6. With Import we claim the ability to write component of React. For those familiar with the principles behind object-oriented programming, component is essentially a type of object, and each time we write code we will expand the component and implement its methods.

class – "Announcing" a new component with its name. At the moment our main component is "App", but it will be able to contain additional components that we will create. Notice that the word extends is placed in the declaration of the component and thus we announce a new component of React.

export default – As import loads a code, with export we actually tell Node.js which code to export, so we can use it with import in another file. The word default is used to specify that if the specific code snippet that we want is not declared, this is the default code snippet.

render – Here React actually comes in. Each React component must contain this function and determines which HTML will be returned to the screen at any given moment in which the component is "live". We will use the word live because we will soon talk about the life cycle of each component. Note that in this project the main component on which we work is always "rendered" to the first screen. It is the highest component in the hierarchy, and the entire rest of the app will be built on it.

 

 

Build a simple application - Manage your shopping list

Now we can start writing our first app.

We'd like to build a shopping list that will support actions:

1. Enter a new entry to the list.

2. Hide the list.

Open a new file called TobuyList.js and copy all the code that appears in App.js to it. Paste the code in the TobuyList.js file and rename the app to TobuyList, and delete the h1 element. This should look like this:

 

 

In our App file, we also delete the h1 and use import to load the new component we created into the DOM by inserting it into the JSX element as in the image:

 

 

We return to the ToBuyList.js file. We would like to insert two buttons into the main div - one to hide / reveal the list and the other to add a record to the list. In addition, we would like to enter an input where we will write the name of the new record and a list ul containing the members of the list. This should look like this:

 

 

 

Props, state, virtual DOM:

In order for us to continue writing in the React, we will stop for a moment and try first to understand a little better how React works:

1. Each component can have properties from parent (props) and these props can be accessed in the code by using "this.props". For example if we want to decide what color should be on our list, we can set on App the TobuyList color:

<TobuyList listColor={'#17bc21'} />

And then we can, from the componant, to access the color by calling this.props.listColor. Notice that we invented the key "listColor" and thus we can give each component any feature we want. In this way you can, for example, render a number of lists that have different colors and are completely separated.

2. Each React component can hold state. The state is an object that can contain lots of keys with values of all types (boolean variables, numbers, strings, and arrays). And can be updated by a special function of React called setState(). Anywhere in the code we can refer to variables in the state by using "this.state".

3. Beyond the DOM we see, React holds in the background of the browser an object which we call the "Virtual DOM". This object contains the whole DOM structure that React renders, and at each setState operation React will look for the exact HTML elements that depend on the state and should be modified. This is actually React's benefit in terms of efficiency and performance.

 

Let's see how we use the state in our componnet. To initialize the state, we call the function called constructor(). This function is called first when a new instance of the component is created. Within this function we will define the initial states of the newly created component. The code will look like this:


 

We need to focus on a few things: 

1. The constructor function gets the argument in the props. We will always write this by default because this way the constructor function will have access to props if they exist.

2. Calling the function super(props) is required in order to call the constructor of the general component of React from which we inherit. For those coming from Object-Oriented languages such as C# or JAVA this looks familiar. If you do not understand this, do not worry, you do not need to understand it at this point.

3. We initialize the state object with three values: Boolean value of isOpen that starts as "true", the new value of the name added to the list when "add" button is clicked (updated each time we change the input), which will be stored in newItemToAdd (initialized as empty string), and our shopping list which is actually an array of items that contains the values "tomatoes", "cucumbers" and "carrots".

 

 

The map function and its use within JSX:

Now the first thing we want to do is print out our shopping list: cucumber, tomato and carrot. In order to do this we will first learn about the map function, which belongs to the Javascript array and is very much in use in React. This function accepts an "invocation function" which accepts as input each element in the array and returns an array of outputs. For example, for the array:

var arr = [1, 2, 3, 4]

If we write:

arr.map(num => num**2) (*)

We get the array:

[1, 4, 9, 16]

Which means squared numbers.

It is possible that some of the article readers will not understand the syntax I have written in a row (*). A function that is registered in this form is called Arrow function or Lambda function. In the same way you can list the row (*) in the line:

arr.map(function(item){return item**2})

But beyond the fact that the first form is more elegant and intelligible, it also automatically inserts "this" reference into the scope of the inner function.

For those who less understands and are interested in the arrow function, you can read more about this topic on this link.

Now let's get back to our componnet. Write down the code:

 

תמונה 3: הרשימה ההתחלתית מרונדרת למסך

 

Now we see on screen:

1. Our input is empty.

2. Add button (still not active)

3. Hide / Show button (still inactive)

4. List of our vegetables.

 

As we see, in order to write Javascript code within the JSX element we have to open braces. We do this within our list ul. We use this.state.items array and for each string it contains, we return a li element with the name of the string. React knows how to take the array of elements that have been returned and render them one by one.

Now if we look at the console it seems that we have received a warning from React:

Warning: Each child in an array or iterator should have a unique "key" prop

This warning is due to the fact that in order for a script to work properly we need to give a unique index to each element generated within the loop under the key value. This can be done using the second argument in the map function:

 

 

 

Update the state

When we build components in React, one of the things we want is to know the status of the app in any given situation. Therefore, we would like each input change to maintain its current value in state. In order to do this, we will add a new function called updateNeItemToAdd (newVal) that will receive the newVal value within the input and read each time the input changes. The update will be done by a special function to update the state called setState. In addition, we will add input onChange to the input. Note that the C is large, because of JSX syntax.

 

 

Notice we wrote:

In other words, every change calls a function that returns a function and inserts the input value. For me, this is a more elegant way of writing code.

Also note that setState gets an object. With this object, you can update several values in state with one stroke.

 

 

Add item to list

Now we will write the ability of the list to add item. First we add a function to the component that will call addItem to update the array of items found in the state of the component. Add the attribute "onClick" to the button, with the function name. In order to do this correctly in terms of memory usage, since we do not want to change the state array directly and interrupt React, we "clone" the items in the state, push the new item to it and then update the state:

 

 

Now we can review the app we've written. Write potatoes in the input and click add. You can see that a record has been added to the list with the name of the word we wrote:

 

תמונה 4: הוספת item לרשימת הקניות

 

 

DOM update

We'll explain what's really going on here: each time we perform setState, React looks for exactly which elements in the DOM are depend on the state, and updates the relevant elements. Therefore, whenever we update the items array in the component, the TobuyList render function is called and updates the list.

 

 

Hide / Show List Function:

Now we'll add more functionality to our list. We want each time you click on the hide / show button, the list will be hidden or displayed, according to the relevant situation. And the correct word on the hide / show button should appear according to the relevant situation.

We'll see the code and then explain it:

 

 

Explanation: We added the toggleList function which the only thing it does is to run setState and replace the boolean value of isOpen within the state.

In addition, in the render function, the element of the button that hides / displays would change like that:

That is, clicking on it triggers the toggleList function and the text inside is a condition of the current state isOpen. That is, each time the state of isOpen changes, React changes the button text according to the relevant Boolean value.

In addition, to our ul list, we have added the condition:

 

That is, whenever the state of isOpen is changed, React decides whether to display the list or insert an empty string into the DOM.

We'll save and it looks like now functionality has been added:

 

תמונה 5: הסתרת / הצגת הרשימה

 

 

Move to several lists, paint them, and set initial items

Now that we have a component that represents a shopping list, we can expand our app to create multiple shopping lists. Each list will have:

1. Name.

2. Color.

3. Initial items (so we can change the values tomatoes, cucumbers, carrots).

 

First, go back to the App.js. Duplicate the TobuyList three times. For each component we put props of its color, its name, and an array of initial values:

 

 

Now, let's go back to the TobuyList file. We will update the constructor items to those coming from the props and add to our input a placeholder that will include our list title:

 

 

 

Adding inline-style in the React:

One last thing we'll do is learn how to give React properties of css in the componet. We want each list to have the color it was given in props.

Important Note: This is basically not recommended and 99% of the time it is best to write the css externally, which is dependent on css classes.

Add to the main div the component TobuyList rernders, attribute named "style". This attribute gets an object that contains keys and values that are identical to css properties. The only change is that keys with more than one word are not writen by the '-' character and instead are writen in the camelCase style.

Let's enter the object under the key backgroundColor the value from props:

 

 

Now save both files and see the result:

 

תמונה 6: React מרנדר 3 קומפוננטות בעלות פונקציונליות זהה אך עם ערכים שונים. ניתן להסתיר כל אחת מהרשימות ע"י כפתור ה-hide המתאים לה

 

Summary

In this tutorial we learned to build the basic cornersote of React - the component. We have learned how to build independent components (modular) that make the programming of large applications easier.


What did we not touch?

There are many things that we have not touched but one of the most important things is the life cycle of each component. For example, there are built-in functions in the component that can be given to any component such as componentWillMount or componentWillUnmount which determine which functions will be invoked before the increase or decrease of a component from the DOM.

More detailes can be found in this link.