React-js Fundamental, Installation of React Js, What is React JS, Flow of React JS

0

ReactJS is a declarative, efficient, and flexible
JavaScript library for building reusable UI components. 

It is an open-source, component-based front-end library responsible only for the view layer of the application.

 It was created by Jordan Walke, who was a software engineer at Facebook. 

It was initially developed and maintained by Facebook and was later used in its products like WhatsApp & Instagram. 

Facebook developed ReactJS in 2011 in its newsfeed section, but it was released to the public in the month of May 2013.

Today, most of websites are built using MVC (model view controller) architecture.

 In MVC architecture, React is the 'V' which stands for view, whereas the architecture is provided by the Redux or Flux.

A ReactJS application is made up of multiple components, each component responsible for outputting a small, reusable piece of HTML code.

 The components are the heart of all React applications. These components can be nested with other components to allow complex applications to be built of simple building blocks.

 ReactJS uses a virtual DOM-based mechanism to fill data in HTML DOM. The virtual DOM works fast as it only changes individual DOM elements instead of reloading the complete DOM every time.

To create React app, we write React components that correspond to various elements. 

We organize these components inside higher-level components which define the application structure. For example, we take a form that consists of many elements like input fields, labels, or buttons. We can write each element of the form as React components, and then we combine it into a higher-level component, i.e., the form component itself. The form components would specify the structure of the form along with elements inside of it.

Traditional Web application Development:-

In Traditional Web Applications, we use HTML, CSS, and JS Code to design UI under application, but in modern web development, we divide the application into two different sub-projects.

the first project contains API and database-related information and the second application contains FrontEnd Design.

React JS and Angular JS both are used to create modern Web application development using React and Angular Front End User Interface.

1)  User Access Layer  (UI/UX)  ----> 

      HTML5, CSS, JS and Jquery

2)  Business Access Layer

       Java, .NET, PHP

3)  Data Access Layer

      Database related code based on technology for Java (JDBC), .NET (ADO.NET), etc

     Modern Web Application Development:-

     Modern Web applications divide the project into two different subparts.

     The first, the part will be implemented by the Design Layer

    The second part will be implemented for the Database and Code Layer.

1)  User Access Layer and Business Layer:-

       React or Angular

2)   Data Access Layer

        Create API using any Server Side Scripting.

What you should learn before REACT-JS?

1)  JS, JSX, JS with ES6

2)  Object-oriented JavaScript or JSX 

What is MERN?

MERN  Means

M  --->  MONGO

E --->   Express JS

R ---->  REACT JS

N --->   NODE JS

What is MVC Architecture?

MVC is the design pattern to distribute the project on different project layers, M stands for Model which is used to create the data access layer, V stands for View which is used to contain the design layer and C stands for Controller is used to contain business code of an application. React Js is used to create the View Layer of an application.

Installation of React-JS?

1)  Install NODE JS in Machine

https://nodejs.org/en/download/

2)  npm install react   

if react is already present

npm view react version

3)  npx create-react-app app-name

4)  cd app-name

5)  npm start

node_modules:-    the base package of reacting that is used to contain all the libraries of a node JS.

public:-

it contains all assets of the project means js, CSS, and images files of an application will be implemented by the public folder.

src:-  it means source, all application components will be defined under src folder. start-up file of 

react application is index.js means when we call 

any application then the first index.js file will be 

called.

What is the flow of react js application:-

In react first index.html file will be loaded that will display the result of index.js and index.js file is the startup file that is used to call the app component of the application using app.js file.'

1) public ---> index.html (provide container to show APP Data)

2) result of a component)----> index.js(calling APP Data)

3) component) ----> app.js(component)  (Create Ressable code)

"we should never write any code on .html, all code"

(design, business logic) will be implemented by the component.




Example of React Life cycle with the mounting operation:-

Mounting means putting HTML elements under the DOM.

import React from "react"
export class Example1 extends React.Component {
    constructor(props) {
      super(props);
      this.state = {a: 1000};
    }
   
    componentDidMount() {
        setTimeout(() => {
          this.setState({a:20})
        }, 1000)
      }
    render() {
      return (
        <h1>{this.state.a}</h1>
      );
    }
  }
 
Updating:-

It means when we change the state of react ui then it will implement updating state.

import React from "react"
export class Example2 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {favoritecolor: "red"};
      }
      shouldComponentUpdate() {
        return true;
      }
      changeColor = () => {
        this.setState({favoritecolor: "blue"});
      }
      render() {
        return (
          <div>
          <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          <button type="button" onClick={this.changeColor}>Change color</button>
          </div>
        );
      }
     
  }
Another Example of Updating:-
import React from "react";
export default class Example4 extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    componentDidMount() {
      setTimeout(() => {
        this.setState({favoritecolor: "yellow"})
      }, 1000)
    }
    getSnapshotBeforeUpdate(prevProps, prevState) {
      document.getElementById("div1").innerHTML =
      "Before the update, the favorite was " + prevState.favoritecolor;
    }
    componentDidUpdate() {
      document.getElementById("div2").innerHTML =
      "The updated favorite is " + this.state.favoritecolor;
    }
    render() {
      return (
        <div>
          <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          <div id="div1"></div>
          <div id="div2"></div>
        </div>
      );
    }
  }


Unmounting:-

When component destroy the element from DOM objects then it is called unmounting.

import React from "react";
export default class Example3 extends React.Component {
    constructor(props) {
      super(props);
      this.state = {show: true};
    }
    delHeader = () => {
      this.setState({show: false});
    }
    render() {
      let myheader;
      if (this.state.show) {
        myheader = <Child />;
      };
      return (
        <div>
        {myheader}
        <button type="button" onClick={this.delHeader}>Delete Header</button>
        </div>
      );
    }
  }
 
  class Child extends React.Component {
    componentWillUnmount() {
      alert("The component named Header is about to be unmounted.");
    }
    render() {
      return (
        <h1>Hello World!</h1>
      );
    }
  }
 

What is a Component?

it is the business class or object of react js that is used to provide the design layer and code layer of an application.

react js is specially used to design single page applications and page components (header, sidebar, footer, content section) will be created by component.

type of component.

1)  Function Component:-

   function Functionname() {

       return ( 

            <div>

          </div>

           )

        }

    export default App;

    export means public accessibility to component

Function Component Example:-

function Addition()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a+b}</p>

       </div>

    );
}

export default Addition;

SI Component Example:-

function SI()
{
    var p=50000;
    var r=2.2;
    var t=2;
    return(
     <div>
       <p>Result is {(p*r*t)/100}</p>

     </div>

    );
}

export default SI;

How to call Multiple Components in React-JS:-

function Operation()
{
 
    return(
       
       <div>
      <Add />
      <Sub />
      <Multi />
      <Div />

       </div>

    );
}
function Add()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a+b}</p>

       </div>

    );
}
function Sub()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a-b}</p>

       </div>

    );
}
function Multi()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a*b}</p>

       </div>

    );
}
function Div()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a/b}</p>

       </div>

    );
}
export default Operation;

Note:-  all exported components can be rendered by index.js.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('root')
);

How to create program logic using components?

function Evenodd()
{
    const x = 11;
    var result;
    if(x%2==0)
      {
          result = "even"
      }
      else
      {
          result= "odd"
      }
    return(
       
       <div>
     
       <p>{result}</p>
       </div>

    );
}

export default Evenodd;

Example of SI Program:-

import { useState } from "react"

function SI()
{
    const[p,setP] = useState(0)
    const[r,setR] = useState(0)
    const[t,setT] = useState(0)
    const[res,setRes] = useState(0)
    function enterP(e)
    {
     setP(e.target.value)
    }
    function enterR(e)
    {
        setR(e.target.value)
    }
    function enterT(e)
    {
        setT(e.target.value)
    }
    function calc(e)
    {
        var si = (parseFloat(p)*parseFloat(r)*parseFloat(t))/100
        setRes(si)
        e.preventDefault()
    }
    return(<div>
     <form>
         <input type="text" onChange={enterP} placeholder="Enter P"  />
         <br/>
         <input type="text" onChange={enterR} placeholder="Enter R"  />
         <br/>
         <input type="text" onChange={enterT} placeholder="Enter T"  />
         <br/>
         <input type="submit" value="SI" onClick={calc} />
     </form>
      {res}

    </div>)
}
export default SI;

Example of Addition:-
import { useState } from "react";

function Hello()
{
   const[a,setA] = useState(0)
   const[b,setB] = useState(0)
   const[c,setC] = useState(0)
   function fun1(e)
   {
        setA(e.target.value)
   }
   function fun2(e)
   {
    setB(e.target.value)
   }
   function add(e)
   {
      var c = parseInt(a) + parseInt(b)
      setC(c)
     e.preventDefault()

   }
    return (<div>

       <form>
         <input type="text" onChange={fun1} placeholder="Enter first number" />
         <br/>
         <input type="text" onChange={fun2} placeholder="Enter second number" />
         <br/>
         <input type="submit" onClick={add} value="ADD" />
        </form>
        {c}
    </div>)
}

export default Hello;

2)   Class Component:-

the class component is used to contain the program code of react component using class and object patterns.

it provides the class pattern to implement component code, we can create a separate section to initialize data members and form attributes under the constructor \and init block. we can implement all features of oop's to create 

1) class-based component.

class Classname extends React. Component

{

       render()

       {

           return ( 


           )

       }

}

Example of class based component in React-JS

import React from "react";

export class Welcome extends React.Component
{
    render()
    {
        return(
         <div>
             <p>Welcome in Class Component in React JS</p>
         </div>
        );
    }
}

Code of index.js

import {Welcome} from './Welcome';

//const x = 11
//var result = <p>{ x%2==0?"even":"odd"}</p>
ReactDOM.render(
  <React.StrictMode>
    <Welcome />
  </React.StrictMode>,
  document.getElementById('xyz')
);

Addition program in REACT JS:-

Addition program using local instance variable

import React from "react";

export class Welcome extends React.Component
{
    render()
    {
        var a=10;
        var b=20;
        var c=0;
        this.c = a+b;
        return(
         <div>
             <p>{this.c}</p>
         </div>
        );
    }
}

Addition Program using global instance variable:-

import React from "react";

export class Addition extends React.Component

{

    state = {

        a: 100,

        b: 200,

        c:0

      };

       constructor()

   {

     super();

       }

   render()

   {

    const { a, b } = this.state;

    //console.log(this.state) ; 

     this.state.c=a+b;

    return(

       <div>

       <p>{this.state.a+this.state.b}</p>

       <p>{a+b}</p>

       <p>{this.state.c}</p>

       </div>

       )

   } 

}

index.js file:-

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import App from './App';

import {Addition} from './Addition'

import reportWebVitals from './reportWebVitals';

ReactDOM.render(

  <React.StrictMode>

    <Addition />

  </React.StrictMode>,

  document.getElementById('root')

);

// If you want to start measuring performance in your app, pass a function

// to log results (for example: reportWebVitals(console.log))

// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals

reportWebVitals();

What is JSX Syntax:-

JSX stands for JavaScript XML.JSX allows us to write HTML in React.JSX makes it easier to write and add HTML in React.

Coding JSX with HTML

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()  and/or appendChild() methods.

JSX converts HTML tags into react elements.

Example 1

JSX:

const myelement = <h1>Welcome in  JSX!</h1>;

ReactDOM.render(myelement, document.getElementById('root'));


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';

const myelement = <h1>Welcome in  JSX!</h1>;
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Example 2

Without JSX:

const myelement = React.createElement('h1', {}, 'I do not use JSX!');

ReactDOM.render(myelement, document.getElementById('root'));

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';

const myelement = React.createElement('h1', {}, 'I do not use JSX!');
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Expressions in JSX

With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:

const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

const myelement = <p>Result is {100+200}</p>
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

Inserting a Large Block of HTML

To write HTML on multiple lines, put the HTML inside parentheses:

Example

Create a list with three list items:

const myelement = (

  <ul>

    <li>C</li>

    <li>CPP</li>

    <li>JAVA</li>

  </ul>

);

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



const myelement = (<ul><li>C</li><li>CPP</li><li>DS</li><li>Java</li></ul>)
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Example

Wrap two paragraphs inside one DIV element:

const myelement = (

  <div>

    <p>I am a paragraph.</p>

    <p>I am a paragraph too.</p>

  </div>

);

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



const myelement = (<div><p>Hello</p><p>Hi</p></div>)
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.

Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent unnecessarily adding extra nodes to the DOM. A fragment looks like an empty HTML tag: <></>. The fragment is the default container of react JS.

Wrap two paragraphs inside a fragment:

const myelement = (

  <>

    <p>I am a paragraph.</p>

    <p>I am a paragraph too.</p>

  </>

);

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



const myelement = (<><p>Hello</p><p>Hi</p></>)
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Elements Must be Closed

JSX follows XML rules, and therefore HTML elements must be properly closed.

Example

Close empty elements with />

const myelement = <input type="text" />;

Attribute class = className

The class attribute is a much-used attribute in HTML, but since JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX.Use attribute className instead.

JSX solved this by using className instead. When JSX is rendered, it translates className attributes into class attributes.

Example

Use attribute className instead of class in JSX:

const myelement = <h1 className="myclass">Hello World</h1>;

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



// myelement = (<><p>Hello</p><p>Hi</p></>)
const myelement = <input type="text" className="ram" />;
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Write .css block:-

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;
}

.ram
{
  background-color: brown;
}

 Conditions - if statements

React supports if statements, but not inside JSX.

To be able to use conditional statements in JSX, you should put the if statements outside of the JSX, or you could use a ternary expression instead:

Option 1:

Write if statements outside of the JSX code:

Example

Write "Hello" if x is less than 10, otherwise "Goodbye":

const x = 5;

let text = "Goodbye";

if (x < 10) {

  text = "Hello";

}

const myelement = <h1>{text}</h1>;

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';


const x = 10
var result = ""
if(x%2==0)
{
  result = "even"
}
else
{
  result = "odd"
}
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(result,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Option 2:

Use ternary expressions instead:

Example

Write "Hello" if x is less than 10, otherwise "Goodbye":

const x = 5;

const myelement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';


const x = 11
var result = <p>{ x%2==0?"even":"odd"}</p>
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(result,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();


Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)