React JS

Skyforce Technologies
Skyforce Technologies
11 min readDec 18, 2020

React JS Basics Tutorial

This tutorial is designed for the one who has some basic idea on what ReactJS is, like what it is used for. So, I will not give any introduction to react. We will jump straight into learning ReactJS. This tutorial will also help you preparing for interview.

Source: Medium.com

As we know react has a component based architecture. So, the idea behind the components created by a programmer is he can reuse those components multiple times anywhere in the application which reduces the repetition of code.

Now, using JavaScript we can make our web pages dynamic, but as our web applications grow in size, it’s difficult for us to handle the complex DOM structure. React makes our tasks easier being a library.

Components — React components are each small part of web UI which we will implement using react, for example header, footer, search bar is a nested component in header etc. and these components gets rendered into UI as HTML.

There are two types of components — Functional component, Class component.

Functional component — In functional component we cannot use ‘this’ keyword of JavaScript.

Here is a simple functional component which shows ‘Hello, World !’ in the webpage. It is a simple ES6 function with some return statement.

import React from 'react';const HelloWorld = () => {
return (
<div>
<h5>Hello, World !</h5>
</div>
);
}
export default HelloWorld

Class component — They are ES6 classes which extends Component from react library.

import React, { Component } from 'react';class Welcome extends Component {
render() {
return (
<div>
<h5>Welcome, User.</h5>
</div>
);
}
}
export default Welcome;

In the above code we can notice that an extra render method is added as compared to functional component and from inside the render method we are returning UI tags. Next how html tags are working inside ES6 classes/functions ??

JSX — Sort of HTML tags inside ES6 classes.

So, in the above code those are not HTML tags, instead they are called as JSX tags. Why JSX? JSX stands for JavaScript XML. We have to admit that we cannot write HTML code inside ES6 classes to return it to the web. So, instead of writing HTML code, we can write JS code to create HTML elements, for example, let me remind you we can create element in JS as below:
document.createElement(“DIV”);
But, in react it works as React.createElement(…). That’s why we import ‘React’ class from React library if you check above. This is the only usage for that import. React creates elements from the JSX tags.
So, when you write JSX tags inside a class, that tag transpiles into react code and next the react code transpiles into JS code and browser renders the created HTML element by JS in the view screen.

Note: We cannot write JavaScript code inside JSX expressions. We can only write variable value and call functions as events.

Props — If we need to pass any property from the parent component to the child component. Remember, children cannot change the property passed from parent, instead the value can be changed for other usage assigning it to a different variable.

So, in react we can have a component holding other components. For example, let’s say in a shopping cart application, we have a parent component called ‘Product’ and child component as ‘Cart’. So when you add a product item to your cart from the products list, you can think like that product item is passed to the Cart component as ‘props’.

How is it passed from parent component? Shown below a parent component where name is being passed as props from parent.

<HelloWorld name="John Doe"/>

Below is the child component receiving the property as props:

import React from 'react';const HelloWorld = (props) => {
const {name} = props //This is object de structuring from ES6. OR
const name = props.name
//In class component we can get props using 'this.props'
return (
<div>
<h5>Hello, {name} !</h5>
</div>
);
}export default HelloWorld

State — Above we learnt that props are the properties that a component gets from it’s parent, so basically the value of properties maintains by it’s parent. But there is also need that a component can maintain it’s own state to which no other components can access. We do that using ‘state’ feature. In a component, state can have variable values etc. to show dynamic values in a web page.

Let’s say in a shopping cart application in the Cart component you can add multiple items to the cart. Each item have their own price. Now, the cart shows you the total amount. The total amount is a state of the Cart component. If you remove an item from the cart, the amount decreases and vice versa. So, Cart component maintains its own total amount state and updates dynamically.

Note: In this tutorial we will discuss state in class components only. Using state in functional component is a different topic called ‘React Hooks’ which we will discuss in another tutorial.

import React, { Component } from 'react';class Cart extends Component {
constructor(){
super();
this.state = {
totalAmount: 0
}
}
render() {
return (
<div>
<h5>{this.state.totalAmount}.</h5>
</div>
);
}
}
export default Cart;

setState — setState helps us to update the state variables or objects value to add dynamic behavior.

setState is a method from the parent class ‘Component’ which we extend while creating a class component. We access setState using ‘this’. We declare a component state and state variables inside the component class constructor as shown below:

import React, { Component } from 'react';class Counter extends Component {
constructor(){
this.state = {
count: 0
}
}
increment = () => {
this.setState({
count: this.state.count +1
})

}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick= {this.increment}>Increment</button>

</div>
);
}
}

export default Counter;

So, you must be thinking, why we need set state. We can simply update the below value like: this.state.totalAmount = 300. But sadly, this doesn’t work. Why? When you are updating the variable, it is actually getting updated, but the component UI is not getting re-rendered. This is the problem. So, you will not be able to see the updated value in the view. To make it work, we use set state which re-renders the UI after updating state each and every time. So, never update state variable directly.

In the above example, when you click the button your view will be updated with proper values. After you click the button, it calls the increment method which in turn uses setState method to update the state variable value and re-render UI. Note: Does it re-renders the total component UI ? No. When react re-renders, then it compares its virtual DOM and the real view DOM. The tag which is updated only that tag gets re-rendered (you can check this by installing react extension in google chrome).

We will discuss onClick event above later in this tutorial. Check here in react the syntax is in camel case so is different from javascript onclick. In React, all DOM properties and attributes (including event handlers) should be camelCased.

setState — Asynchronous

The setState method call is asynchronous call. We do not know exactly when it will get executed after we make a call. So, after set state method gets called/executes, it first update the value then re render. So, if you want to do any task only after the state is updated, then you have to use the callback function inside setState method as shown below. For example if you want to use the updated value from the setState call, then you have to use callback function.

increment = () => {
//Set state is async call
this.setState(() => ({
count: this.state.count + 1
}),
() => {
//Want to do some tasks only after the state is updated.
})
//Want to do some tasks, and we don't care if the state updated immediately.

}

Event Handing — An event gets triggered to perform an action when an user clicks any button or presses any key etc. in your application.

Below is an example shown, when in a shopping cart you click ‘+’ or ‘-’ button to increase/decrease quantity of your item. So, when you click, an event gets triggered to perform an action which is to increase/decrease the number of items in this case. Let’s see below how:

//Functional Component
import React from 'react';
const Cart = () => {
const increaseQuantity = () => {
//Logic to increase item quantity in cart.
}

return (
<div>
<button onClick={this.increaseQuantity}>Click</button>
</div>
)
}
export default Cart

Note: If you see the above code properly I have used this.increaseQuantity without braces, which means I have used the event as a function reference and not as a function call like this.increaseQuantity(). Because if you use it as a function call then while loading the component(i.e. when the web page loads) without clicking on the button, the event gets fired. So, if your event fire action is to change state of the component(usage of setState), then when the page loads your event fire will be in infinite loop because setState again re-renders component which in turn makes the event gets fired again without clicking on the button.

Event Binding — Do I need to be aware of this always?

You will come into an issue with event binding if you use normal JavaScript function as your action method, because when you use normal JavaScript method without binding, ‘this’ keyword will return ‘undefined’ because it is not getting called using object as a reference. Instead it is getting called as standalone function and which in turn returns ‘window’ object. And if strict mode is enabled in JS/ES6 it will return ‘undefined’. But, if you use arrow function as I am using above you will never face event binding issue or you do not need to bind an event. So, I will suggest always use arrow functions to avoid event binding issue.

Important — Props — Above we learnt that a parent can pass properties (variables) to the child using props. What if child needs to call any parent method? Is it possible? Yes. Parent passes it’s own function reference as props to the children component so that children component can raise parent class function events by passing its state variables as method parameters or just normally calling the function reference. Let’s discuss, we will see it’s use case later.

import React, { Component } from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends Component { parentHandler = (childStateValue) => {
alert(`Hello I am parent method getting called from child component which passed its state 'count' variable value: ${childStateValue}`)
}
render() {
return (
<div>
<ChildComponent parentHandler ={this.parentHandler}/> //Passing function ref as props here
</div>
);
}
}

export default ParentComponent;

In the above parent component we are passing the ‘parentHandler’ method as props to the child component below.

import React, { Component } from 'react';class ChildComponent extends Component {
state = { count: 1 }
render() {
return (
<button onClick={() => this.props.parentHandler(this.state.count)}>
Child Component
</button>

);
}
}

export default ChildComponent;

So notice, in the above child component while event action calling whenever you need to call any method with parameters either the method is in the component or in parent you always have to use arrow function to call. Why? We discussed above that we only need to use function reference. So if you try to use arguments you have to add braces which means you are not using function reference, instead you are doing function call. So, you can give a function reference as shown above. Behind it is working like, we are giving a anonymous function reference which in turn calling our function with arguments.

Below is the output when you click the above button in the child component above.

Conditional Rendering — if/else or ternary operator

If you want to render component UI based on some conditions then use conditional rendering. Remember, you cannot use if/else or ternary(JS code) inside JSX tags.

Best approach: Ternary Operator as shown below:

import React, { Component } from 'react';class ConditonalRendering extends Component {
constructor(){
super()
this.state = {
condition: true
}
}
render() {
return this.state.condition ?
<div>If condition is true, show this</div> :
<div>Else show this.</div>

}
}

export default ConditonalRendering;

What if you want to show something in UI only when the condition is true and when false you do not want to show anything. We will use ‘short circuit’ operator(&&) at that time as shown below.

import React, { Component } from 'react';class ConditonalRendering extends Component {
constructor(){
super()
this.state = {
condition: true
}
}
render() {
return this.state.condition &&
<div>Rendered only if the condition is true.</div>

}
}

export default ConditonalRendering;

Lists Rendering — It is same as JavaScript List. It uses map method to iterate the list.

Below is an example how you can render a list of data. For example, let’s say we received some JSON data on an API call, here it’s employee data I hardcoded and suppose you want to display employee details in the view.

import React, { Component } from 'react';
import EmployeeDetails from './EmployeeDetails'
class Employee extends Component {
constructor(){
super()
this.state = {
employeeData: [
{
'id': 1,
'name': 'John Doe'
},
{
'id': 2,
'name': 'John Smith'
},
{
'id': 3,
'name': 'John Clark'
}
]
}

}
render() {
const employeeList=
this.state.employeeData.map((employee) =>
<EmployeeDetails key={employee.id} employee={employee}>
</EmployeeDetails>
)


return (
<div>
{employeeList}
</div>
);
}
}

export default Employee;

Here, first before rendering UI, we mapped the data in a variable. If you notice, we are mapping each employee with employee details component and storing it in a variable. Later, when we are rendering, we just use that variable to render it into UI. In real scenario where we have large set of data, we use a separate component as shown above(EmployeeDetails) and we call that component sending props from this component while mapping inside a variable.

import React, { Component } from 'react';class EmployeeDetails extends Component {
render() {
const {employee} = this.props;
//const employeeKey= this.props.key;
return (
<h5>{employee.name}</h5>
);
}
}

export default EmployeeDetails;

Key — If you have noticed above, we have used a key attribute while mapping. You have to use a key attribute while iterating. Otherwise, you will get below warning:

<EmployeeDetails key={employee.id} employee={employee}>
</EmployeeDetails>

As you can see, along with employee the key is also passed as props. But if you try to access that props inside EmployeeDetails component you will come into below error:

const employeeKey= this.props.key;

So, we should never access key as props in child component. Instead if you need to access it, pass the key value with different prop name.

Now, why we need this key?

Keys always must be unique for each list item when you are displaying them in UI. They help react to identify and re-render the list item when that specific item gets change in the list (In this case an item is h5 in EmployeeDetails). React always compares the virtual and real DOM. If there are any addition of an item to the beginning list, react re-renders the whole list. To increase this efficiency, it uses keys to identify and re-render specific list item. If you use same existing key value of an item to another item you will get below warning:

Now, suppose if you do not have keys for the item list you fetched, then you can use index of the item as key as shown below:

this.state.names.map((employee,index) => 
<p key={index}>{employee.name}</p>
)

That’s all for React basic tutorial. Hope you enjoyed :) Next topic to learn React Hooks.

--

--