RoadToWebDev Day#11 — Introduction to React-JS

Radhika Sheth
8 min readDec 13, 2020

This is a part of my ongoing series about exploring the Road To Web Development, you can find rest of the blogs here

What is React JS?

React is a front-end JavaScript library developed by Facebook which is used to develop interactive UI’s (User Interfaces).

ReactJS is only a front-end library and not the whole framework, which deals with the View component of MVC (Model View Controller).

It is currently one of the most popular JavaScript front-end libraries which has a strong foundation and a large community supporting it.

Why React JS:

The main point is to differentiate a framework without React JS Vs a framework with React JS.

  • In previous frameworks that used the traditional data flow, whenever any data is updated or edited at the backend the browser reloads the web page and repeats the whole process again. In this process, the browser creates a Document Object Model each time changes are made in the data. This repeated creation of DOM results in unnecessary memory wastage and a decrease in application performance.
  • Whereas, React renders the view components with updates or new data and then places the new view in place of the old one whenever any changes in the backend are noted. As a solution to the memory wastage due to DOM, React introduced Virtual DOM.

Virtual DOM:

The re-rendering of the real DOM makes it slow, as it has to be re-rendered each time a change occurs. In order to make this process faster, a Virtual DOM is used.

The virtual DOM is only a virtual representation of the DOM. So whenever any change occurs, the virtual DOM gets updated rather than the real DOM. Here in React, every UI piece is a component, and each component has a state. Whenever the state of a component changes, React updates the virtual DOM tree. Then react performs a process called diffing that is comparing the current version of virtual DOM with the previous version of virtual DOM.

After knowing the changes in the virtual DOM objects, react updates only those changes in the real DOM. So this feature makes the process of rendering faster. And as react uses virtual DOM, it can be included in react’s one of the great features.

And this rendering is done by the render() method.

JSX:

JSX stands for JavaScript eXtension. JSX allows us to write HTML elements in JavaScript and it also converts HTML tags to react elements.

JSX is not compulsory to be used in react, but it has some pros that make it more suggestive.

  • It is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript.
  • It makes it easier for us to create templates.
  • Instead of separating the markup and logic in separated files, React uses components for this purpose.

Example of using JavaScript expressions in JSX:

import React from 'react';
import ReactDOM from 'react-dom';
var name = "Radhika";var element = <h1>Hello, { name }.< /h1>;ReactDOM.render(
element,
document.getElementById("root")
);

JSX elements are treated as JavaScript expression, they can be saved as a variable, passed to function, or stored in an object or array.

Each JSX expression must have exactly one outermost element. Usually wrap the JSX expression in a <div></div>.

Rendering the JSX element means making it appear on the screen.

Rendering Method:

In order to render an element into the DOM:

  • It is necessary to have a root DOM element. Most commonly it is a div element with id = ‘root’ or id = ‘app’ which can be used as the root DOM element.
<div id="root"></div>

We call this a “root” DOM node because everything inside it will be managed by React DOM.

  • The element to be rendered should be defined properly.
const element = <h1>Hello, world</h1>;
  • And finally executing the rendering function that is ReactDOM.render().
ReactDOM.render(element, container[, callback])

In a simpler language, the syntax will be:

ReactDOM.render(What to render, Where to render)

This method renders a React element into the DOM in the supplied container and return a reference to the component (or returns null for the stateless component).

If the React element was previously rendered into container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.

If the optional callback is provided, it will be executed after the component is rendered or updated.

For an instance, the following code will help us to print Hello World.

import React from 'react';import ReactDOM from 'react-dom';const Element = <h1>Hello World! < /h1>;ReactDOM.render(Element, document.getElementById("root"));

Components :

The component is one of the building blocks of React. Components help the programmer to build UI in a better and easy way. UI can be broken in multiple components and these components can be worked on independently. Finally these components are merged into a parent component which can be the final UI. React components are usually kept in PascalCase. (like ThisIsMyComponent)

Kinds of components in React:

  1. Functional Component:

Functional components are simply javascript functions

import React from "react"
import ReactDOM from "react-dom"
function Example()
{
return(
<ul>
<li> Not </li>
<li> A </li>
<li> Human </li>
</ul>
);
}
);

The functional components are rendered with the help of ReactDOM.render().

ReactDOM.render(<Example /> , document.getElementById('root'));
  • The import React from “react” statement allows to use JSX.
  • The import ReactDOM from "react-dom" statement imports the required dependencies when using React.DOM.render() method.

2. Class Components:

The class components are similar to classes in OOP and, it extends “Component” from the dependency which will bring us very useful specifications. And that makes the Class Components unique and useful.

The import from “react” statement will include {Component} in order to get the required specifications from the dependency.

import React, { Component } from "react"
import ReactDOM from "react-dom"
class App extends Component{
render(){
return(
<div>
<h1> Hello world! </h1>
</div>
)
}
}
export default App;

Every class component needs at least one method and that is render() method.

render() method can be compared with the function of the functional component. Both have the return statement and, works also the same. Then,

Why Class Components?

The most important feature of the class component is that it enables to use the states of a component, that is not available with functional components.

Unlike Functional Components, Class Components are able to interact with the other Class Components, sharing the data.

LifeCycle methods can be used only with the class components.

Props:

Props are arguments passed into React components via HTML attributes.

Whenever an element representing a user-defined component is found, react passes JSX attributes and children to this component as a single object and that is nothing but prop.

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Radhika" />;
ReactDOM.render(
element,
document.getElementById('root')
);

What happens exactly is :

  1. ReactDOM.render() is called through <Welcome name="Radhika" /> element.
  2. React calls the Welcome component with {name: 'Radhika'} as the props.
  3. Welcome component returns a <h1>Hello, Radhika</h1> element as the result.
  4. React DOM efficiently updates the DOM to match <h1>Hello, Radhika </h1>.

State:

The state of the component can be said as an object that can store a value and that value can be changed over a lifetime of that component.

In other words, it is the data that the component maintains, or can change its value.

To use state, the component needs to be class-based.

The difference between states and props is props cant be change along the time while states can.

We need to initialize the state first in order to use it in the future. And that can be done by defining the State in the constructor of the component’s class.

class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
lang: "React"
};
}
render() {
return (
<div>
<h1>Let's learn {this.state.lang}</h1>
</div>
);
}
}

this.state.propertyname syntax is used to print or return the state of the given component.

To change the state of a component,this.setState() method is used.

//Correct way
this.setState({attribute: "new-value"});

The state cannot be updated by changing it explicitly without the setState() method.

//Incorrect way
this.state.attribute = "new-value";

When the setState() function is found by the react, it automatically calls the render function and do the changes in the DOM.

The class method containing the setState() method has to be bind with that class.

class InputSong extends Component{
constructor(){
super()
this.state = {
PersonName : "",

}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event){
const {name, value} = event.target
this.setState({
[name] : value
})
}
render(){
return(
<div>
<form>
<input
type = "text"
name = "PersonName"
onChange = {this.handleChange}
/>
<br />
<button >Submit</button>
</form>
</div>
)
}
}
export default InputSong;

In the above example, the handleChange(event) method is used to update the value of the state as the user enters. The value is to fetched by “event.target. value or .name ” as required.

This example also shows the way to work with react forms.

Component Lifecycle:

The lifecycle of a component can be called the series of events that a component goes through from its birth to death.

There are four stages in any component’s lifecycle:

  • Initialization: In this stage, the component is born or constructed with given props and default state.
  • Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.
  • Updating: Updating is the stage when the state of a component is updated and the application is repainted.
  • Unmounting: tIn this final step, the component is destroyed or removed from the code.

For getting detailed knowledge about lifecycle and its methods, you can refer to this video:

React Events:

React events are just like the JS DOM events, but with some difference as:

  • The event handlers in React are kept in curly parentheses.
  • They are in camel case, rather than lowercase
class Exam extends React.Component {
result() {
alert("Passed!");
}
render() {
return (
<button onClick={this.result}>Wanna know the result!?</button>
);
}
}

Concluding this article, hope you got to know the basics and for some hands-on practice, I insist to go through the below-mentioned link.

References:

--

--