REACT BEGINNER and REACT HOOK — useState

12 min readFeb 23, 2022

I know I have been on MIA, but I am still exploring the web development/internet world. As you know, I’m interested in the front-end area, and last time, I focused on Tailwind CSS. Still in the same area, I am trying React.js. Today, I want to show you how to create User Interface using React. Ready to learn for some more?

What is React? Apparently, React.js was developed by Jordan Walke and his team from Facebook, to address their need for a dynamic and high performing User Interface (UI) . It is a JavaScript library that is responsible for rendering UI components. It supports both frontend and server-side.

According to StackOverFlow survey, React.js is the most commonly used web framework in 2021. Why so? Because React.js has many advantages, such as:

1. It uses JSX, instead of JavaScript. JSX is an XML-like syntax for template creation. It is extension to JavaScript that accepts HTML quoting, therefore makes it easier for subcomponents to render.

2. It uses Virtual DOM to allow developers to build lightweight and scalable web apps. This model allows changes in the virtual memory before rending the final webpage into the browser. Whatt??? In simple word, it means that the model allows virtual DOM to refresh only parts of the page, instead of full page. In short, this model increases performance and creates faster programming.

3. It has re-useable code components; thus developers can save time (from repeating themselves. Remember the concept DRY — do not repeat yourself)

4. Website pages are rendered completely, using React.js; from the server to the browser, thus improve the SEO of your web app.

5. It is easily readable (https://www.cognitiveclouds.com/insights/what-is-the-difference-between-react-js-and-react-native/ )

6. Lastly, React.js uses one-way downward data to ensure any changes in child components will not affect the parent components.

Enough with the background, now straight to the learning. I followed Eve Porcello’s course on learning React.js. If you don’t have access to LinkedIn Learning, or you don’t want to watch the video and just want to quickly look up how to write react code to create elements, components, or using react Hooks, then just keep scrolling down.

Before you start, you need to make sure that you have node and npm installed. How to check them? Easy! Create a folder where you want to save your project is. In this case, I have a folder named me-cocktails. Use the terminal in Visual Studio Code (or whatever IDE you prefer), go to the newly created folder directory, then type “node -v” (to check the version of node), and type “npm -v” (to check the version of npm. Once you confirm if node and npm are installed, you can build a web page using create-react-app.

Checking the version of node and npm, then create a React project

However, if you don’t want to install anything, you can use codesandbox.io, to create React project the same way (use create-react-app). In addition, to help you debug React, you need to install React Developer Tools for Chrome (or Firefox, depending on which browsers you will be using).

I am going to use node and npm to build my project. So, Let’s get started!

My objective is to create a drink library, using open brewery API. I should do is to go to drink-library directory, before I can run my project. Type npm start in the terminal window and a page will pop up. The page you see on the browser is actually the function App() located under ./src/App.js file. This function is rendered in ./src/index.js file, through import function.

How to render App function in React

Instead of importing App from ‘./App’, we can write App() function directly above ReactDOM.render();
ReactDOM.render takes 2 arguments: element that we want to create and where we want to render that element.

If we want to create an element, we can use React.createElement() function, which takes 3 arguments: name of the tag (eg. h1), any properties we want the element to have, and the children. After creating an element, we can render it to the root element.

How to send arguments in createElement()

Where is this “root” element located at? It is actually a div element written in index.html file under public folder. It turns out, we still need html file to build a website!

Element of “root” in index.html file

Also, this public folder is useful when we are ready to build app for production (for example, before deploying it to Netlify). Our build file will be published in this public folder.

ADDING PROPERTY

In React.createElement function, the second argument takes in a property value. Initially we set it to null. If we want to assign a value, we will write it as how we write inline CSS. For example, we want to change the h1 font color to green, we can write it like this:

Rendering element with properties

RENDER MULTIPLE ELEMENTS

So far, we could only render h1. What should we do if we want to render multiple elements, such as item lists? We can nest all the createElement function under a ul tag like this code:

Render multiple elements in React

However, if we want to render more complicated elements, we need JSX, a JavaScript XML, which allow to write HTML in React. How do we do that? Using the code above, instead of sending three arguments using React.createElement(), we will write it as HTML code: power of JSX.

Rendering element with JSX

How did React achieve this? Apparently, there is a tool behind the whole scene called Babel. It is a JavaScript compiler, the one that allows you to write a code that doesn’t work in the browser yet, either because it is a new syntax or it is not supported, like JSX.

If you don’t want to write the code in your personal IDE, you can use babeljs.io, find “Try It Out” and copy the code there.

Even though there are many similarities between JSX and HTML, there are also differences, such as: dynamically assigned variable.

Let’s say we have a variable that we want to assign dynamically to the code, we can assign the value into a variable, as such code below:

Assign value dynamically through JSX

We can also assign a JSON object (with key-value pairing format) to the dynamically assigned variable and access their value individually.

Assign JSON object through JSX

We can also combine CSS into JSX, however, in HTML class is called className in JSX.

Let’s say we have a CSS class called cool-drink, and we write it as below:

CSS code with class of “cool-drink”

We can incorporate the CSS class into JSX by writing it as the code below:

JSX className in React

CREATE REACT COMPONENT

In React, component is collection of elements, that are used to build the front-end. Component contains independent reusable pieces, a function that returns some UI. In previous examples, we had a component created automatically by React, called App. We can continue creating components in this App.js file, but for today’s example, I will write all the functions to create component under index.js file, for easier explanation (so we don’t have to flip back and forth between two files; but, in your practice, try to organize your file properly).

Okay, we know we want to write our own component, and render whatever we want. But, if we want to send the many elements, the way to do it is to return the div element through a function and render the function, instead of rending the whole div element.

Create React component and render them

We can also return a whole div with more elements in it.

Multiple element tags under the div

REACT PROPERTY

Let’s talk about property. Property is an object in React that contains properties about the components. With props we can display dynamic data in component. To begin, let’s write an argument to the function Hello() and pass it by adding library and message, like the one below:

Incorporate properties into React components

As we know, string and integer (number) are used differently in variable. Instead of using quotation mark, we use curly bracket to pass the value in React. If we want to add a number, as a value, instead of just string, we pass it inside curly brackets.

Passing number as property’s value

We can also pass function to this JSX template, first thing you need to do is console log the object, then we can use the length of the props instead of assigning a value in props.number. Let’s add a message in the props, and use the length of the props.

Accessing the properties’ length

COMPOSING COMPONENT

In a different scenario, we have two different functions or components. Let’s say I want to nest the first component into the second component, we can render the second component like the code below:

Render two components using React

We could also just render the name using name only, instead of props.name. However, if we have a list, we need to use map function, with a little bit of JavaScript.

Render a list using map function in React

RENDER LISTS OF OBJECTS

Now, instead of just an array like list, we have a JSON object of list. How do we render those? Check the code below:

Rendering an object through map function

However, using the method above, you will get a warning.

Warning of missing unique key

How do we make the warning go away? We need to assign unique “key” prop as per warning’s suggestion, in the div element.

Now what if we have a number list? How do we add the key? Would you be confused with which one is the key which one is the actual value? We can just use toString() function like this:

Use toString() to map the unique key

Another way to add the unique key to a numbered list is to add an identifier.

Use map(item, i) ad an identifier to assign the unique key

CONDITIONAL RENDERING

As we know, we have an option of conditional statement to perform different actions based on different condition. We can also apply this conditional statement in React, called conditional rendering. How and where should we write the if condition? There you go; in case if you are hungry then order Wings, otherwise, if you are thirsty, then order Margarita:

Else If conditional statement rendering in React

What if you are not hungry or thirsty? What would you do? Let’s add one more line of code, but also rewrite the else if conditional into shorter code.

Different way of writing else if — else conditional rendering

REACT FRAGMENTS

Using example above, what if you want to order both Food and Drink? We need to send all these components at once using div. Can you imagine how many divs we need? To make it simple, we can use <React.Fragment> </React.Fragment> or, in short, <> </>.

Rendering two components at once using React.Fragment

We also can write it simpler by eliminating function App() and just render the component under ReactDOM.render()

DESTRUCTURING ARRAY

Let’s work with array now. As we know, we use index to access array’s value, and the index value starts from 0. We will add an array called snacks at the very bottom of the line, after ReactDOM.render, and print the value of the array based on index we assign (from 0 to 2). Pretty simple array stuff right?

Now, we will do it in array de-structuring way. React uses JavaScript ES6 to do this. Instead of using a numbered index, we name the index with anything we want, without the variable. When printing the value, the console.log now is taking an argument of whatever name we assigned for the index. Check out the code below to understand it better (pay attention on the const [first] naming; we no longer use the snacks as the array variable name).

Array destructuring replaces snacks[0] with first

We can also keep going to add more name, and keep printing the value of the next index, like below:

Additionally, we can skip the variable name in the middle, if you want to ignore them.

But, how is it useful, you ask? We can use array destructuring to combine it with React hooks. Just keep reading…

REACT STATE WITH HOOKS

What is hooks? Hooks are functions, and are used to allow function components to have access to state, fetch data, and interact with browsers. Hooks, in React, always start with use, whether it is useState, useReducer, useEffect, and so on. In order to use hooks, we need to import the use, for example: { useState }. UseState is a built-in hook that is used to handle state changes in application. In HTML, we call this functionality as a changed event (like onClick, focus, input, etc). For more example, check out Eve Porcello’s course.

One thing to note is that when writing const, using hooks and array destructuring, it always returns a function; therefore, we always have it written as const [name, functionName], like code below.

Change status when button is clicked, using React Hooks

Code above uses button to change the event. Now, instead of just changing the state, let’s do some math. We want to add a functionality where every time a button is clicked, it will increase the set year by one. Here how we do it:

Setting a number as initial value, then use onClick() function to increment the year

Next, we will create star ratings, using React, where by default, we will have 5 stars, however, when defined, we will have as many as stars the user wants. In order to create stars, we need icons from the library.

How to install react-icons using npm

Thus, we need to install react-icons before proceeding with the code below.

But, the stars has black color?? Who ever seen rating with black color? So unattractive! Don’t worry, let’s add a property to it. Using useState, we need to be able to access the unique key properties, so that we can access all the stars. Here how we write the code for it.

I will end my blog here, as it is a lot to take at once. Digest them, and practice, then go back for the next blog, where I am going to talk about useEffect, useReducer, how to create custom hooks, as well as deployment in Netlify. Thanks for reading :)

--

--

Julie Gunawan
Julie Gunawan

Written by Julie Gunawan

Tech enthusiast, interested in backend and DevOps

No responses yet