React JS: A JS library for building UI

React JS: A JS library for building UI

February 18, 2020
React Js

What is React Js?

React Js is a JavaScript library created by Facebook for building user interfaces (UI). It is used to build single-page applications and allows us to create reusable UI components.

Introduction to the DOM

What is the DOM?

A programming API for documents.

The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an XML or HTML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them one can change the structure, style or content of a document. Nodes can have event handlers attached to them. Once an event is triggered, the event handlers get executed.

Press F12 key and click on console tab in Web Developer Inspector. write below command in console.

> document
> console.dir(document);

What can we do with the DOM?

1. Get an element in Javascript

> getElementByID()
> getElementsByClassName()
> getElementsByTagName()
> querySelector()
> querySelectorAll()

Example:

<!doctype html>
<html>
  <head>
    <title>The DOM Example</title>
  </head>
  <body>
    <h1 id="heading">Get an element in Javascript</h1>
    <ul class="list">
      <li>You can see how pages are made</li>
      <li>You can manipulate it</li>
    </ul>
  </body>
</html>
> document.getElementById("heading");
< <h1 id=​"heading">​Get an element in Javascript​</h1>​

2. Create things in the documents:

> createElement()
> createAttribute()

Example:

var para = document.createElement('p');
para.innerHTML="This is paragraph element created from javascript";
document.body.appendChild(para);
var attr = document.createAttribute("class");
attr.value="class-para";
para.setAttributeNode(attr);

Problem:

How would you implement getElementsByAttribute?

getElementsByAttribute('data-js-name', 'foo')
<div data-js-name="foo">

Suggested Steps

> Get all of the elements in the DOM
> Check if they have a particular attribute
> Check that the attribute has the correct value

The easy way:

function getElementsByAttribute(att, val){
	return document.querySelectorAll('[' + att + '=' + ']');
}

Solution: Find a DOM node

function getElementsByAttribute(attribute, value){
	var all=document.getElementsByTagName('*');
	var found = [];
	for(var i=0; i<all.length; i++){
		element = all[i];
		if(all[i].getAttribute(attribute)==value){
			found.push(all[i]);
		}
	}
	return found;
}
getElementsByAttribute('class', 'blog_title');

Events and Callbacks

Events: Occurrences that happen in the browser

Common Events:
> click:	the users clicks
> resize:	the user resize the document
> mouseover:	a mouse is moved over an element
> load:		a resource has finished loading
> keydownn | keypress | keyup:	the user interacts with the keyboard

Example: Callbacks

window.addEventListener('load', function(event){
	console.log("All resources finished loading!");
});
<!doctype html>
<html>
  <head>
    <title>Events and Callbacks are sick</title>
  </head>
  <body>
    <h1 class="header">Events and callbacks are SO fun.</h1>
    <button id="one">Button 1</button>
    <button id="two">Button 2</button>

    <script type="text/javascript" src="handlers.js"></script>
  </body>
</html>
document.getElementById('one').addEventListener('click', function() {
  console.log('you clicked the button!');
});

document.getElementById('two').addEventListener('mouseover', function() {
  document.getElementById('two').innerText = 'you hovered over me!';
});

document.body.addEventListener('timeEvent', stateTime);

function stateTime(e) {
  alert("event time is: " + e.detail);
}

var myEvent = new CustomEvent('timeEvent', {
  'detail': new Date()
});

Prerequisite of learning React

Before learning with React, you should have knowledge of:

  • HTML
  • CSS
  • JavaScript
  • Knowledge with the new JavaScript features introduced in ECMAScript 6 (ES6)

Example

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  render() {
    return <h1>Hello Stately World!</h1>;
  }
}

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

Note: We will discuss about this example in detail. let’s first start with environment setup.

Set up a React Environment

Firstly, to run react code on your system you have NPM and Node.js installed. The create-react-app is an officially supported way to create React applications. Install create-react-app by running below command in your terminal:

C:\Users\Your Name>npm install -g create-react-app

Run below command to create a React application named reactapp:

C:\Users\Your Name>npx create-react-app reactapp

Run the React Application

Run below commands to run react application reactapp:

C:\Users\Your Name>cd reactapp
C:\Users\Your Name\myfirstreact>npm start

After running above command you will see in a browser window will pop up with your newly created React App! If not, open your browser and type localhost:3000 in the address bar.

How does React Work?

React creates a VIRTUAL DOM (VDOM) in memory. Instead of manipulating the browser’s DOM directly, React creates a virtual DOM in memory, where it does all the necessary manipulating, before making the changes in the browser DOM. React only changes what needs to be changed! React finds out what changes have been made, and changes only what needs to be changed.

How to start?

If you’re interested in playing around with React, you can use an online code playground. Try a Hello World template on CodePen, CodeSandbox, Glitch, or Stackblitz. If you prefer to use your own text editor, you can also download this HTML file, edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so we’d only recommend using this for simple demos.  

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    
    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

      ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('root')
      );

    </script>
    <!--
      Note: this page is a great way to try React but it's not suitable for production.
      It slowly compiles JSX with Babel in the browser and uses a large development build of React.

      Read this section for a production-ready setup with JSX:
      https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project

      In a larger project, you can use an integrated toolchain that includes JSX instead:
      https://reactjs.org/docs/create-a-new-react-app.html

      You can also use React without JSX, in which case you can remove Babel:
      https://reactjs.org/docs/react-without-jsx.html
    -->
  </body>
</html>

  To “remember” things, components use state.  

React Component

There are two types of components in react js:

  1. Function Component
  2. Class Component

Function Component:

Function Components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen. In React, function components are a simpler way to write components that only contain a render method and don’t have their own state. Instead of defining a class which extends React.Component, we can write a function that takes props as input and returns what should be rendered. Function components are less tedious to write than classes, and many components can be expressed this way.

Example:

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

Class Component:

Example:

Class Components are ES6 classes. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

class Welcome extends React.Component {
    render() {
      return <h1>Hello, {this.props.name}</h1>;
    }
  }