Notes of ReactJS

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 11

Introduction of React JS

--------------------------
React is a JavaScript library for building user interfaces.
React is used to build single-page applications.
React creates a VIRTUAL DOM in memory.
React only changes what needs to be changed!

React is one of the most popular front-end JavaScript libraries in the field of web
development. It is mainly maintained by Facebook and a large community of
developers. A number of large, established companies (Netflix, Instagram, Airbnb,
to name a few) use it to build their user interfaces and UI components

It uses virtual DOM (JavaScript object), which improves the performance of the app.
The virtual DOM works fast as noteit only changes individual DOM elements instead
of reloading complete DOM every time.
React uses Virtual DOM, thereby creating web applications faster. Virtual DOM
compares the components’ previous states and updates only the items in the Real DOM
that were changed, instead of updating all of the components again, as conventional
web applications do.

It was created by Jordan Walke in May 2013, 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.

React Component
---------------
-Components are the building blocks of any React application, and a single app
usually consists of multiple components.
-A ReactJS application is made up of multiple components.
-A component must define a render method that specifies how the component renders
to the DOM.

-React employs one-way data binding-


React follows a unidirectional data flow. This means that when designing a React
app, developers often nest child components within parent components.

-React is easy to learn, as it mostly combines basic HTML and JavaScript concepts
with some beneficial additions.

-It can be used for the development of both web and mobile apps(using ReactNative)

Create React App


---------------------
To use React in production, you need npm which is included with Node.js.
The create-react-app allows you to create and run React project very quickly.

1)Install Node.js & NPM


Node version >= 8.10
NPM version >= 5.6

2)Install CRA
npm install -g create-react-app

3)create a new React Project using CRA


create-react-app myapp
4)Now, we need to start the server so that we can access the application on the
browser. Type the following command in the terminal window.
myapp>npm start

Project Anatomy
-----------------
node_modules: It contains the React library and any other third party libraries
needed.

public: It holds the public assets of the application.


It contains the index.html where React will mount the application by default on the
<div id="root"></div> element.

src: It contains the App.css, App.js, App.test.js, index.css, index.js, and


serviceWorker.js files. Here, the App.js file always responsible for displaying the
output screen in React.

package.json: It holds various metadata required for the project. It gives


information to npm, which allows to identify the project as well as handle the
project's dependencies.

___________________________________________________________________________________
________________

React Component
---------------

Components are javascript functions that return HTML elements

In ReactJS, 2 types of components


1)Functional Component
2)Class Component

1)Functional Component
-----------------------
A Function component returns HTML.It can be written using much less code.
The functional component is also known as a stateless component because they do not
hold or manage state.

Example:-
Welcome.js
------------
function Welcome(){
return <h1>Welcome to the World of Functional Components!!</h1>
}
export default Welcome;

App.js
-------
function App() {
return (<div><Welcome/></div>)
}
export default App;
___________________________________________________________________________________
__________
2)Class Component
------------------
When creating a React component, the component's name must start with an upper case
letter.

The component has to include the extends React.Component statement, this statement
creates an inheritance to React.Component, and gives your component access to
React.Component's functions.

The component also requires a render() method, this method returns HTML.
The class component is also known as a stateful component because they can hold or
manage local state.

Example:-
Hi.js
------
import React from "react";
class Hi extends React.Component{
render(){
return <h1>Hi from Class Component!!</h1>
}
}
export default Hi;

App.js
-------
function App() {
return (<div><Hi/></div>)
}
export default App;
___________________________________________________________________________________
__________

Props
-----
props stands for properties
Props are arguments passed into React components.
Props are passed to components via HTML attributes.
It gives a way to pass data from one component to other components.
Props are immutable so we cannot modify the props from inside the component.
Components receive data from outside with props,

Example 1:-Using Props in Functional Component


Welcome.js
-----------
function Welcome(props){
return <h1>Welcome {props.name}!! to the World of {props.company}</h1>
}
export default Welcome;

App.js
-------
function App() {
return (
<div>
<Welcome name="Rahul" company="Seed"/>
<Welcome name="Rohit" company="IBM"/>
</div>
)
}
export default App;

Example 2:-Using Props in Class Component


Welcome.js
-----------
class Welcome extends React.Component{
constructor(props){
super(props);
}

render(){
return <h1>Hi {this.props.name} from {this.props.company} Class Component!!
</h1>
}
}
export default Welcome;
App.js
-------
function App() {
return (
<div>
<Welcome name="Rahul" company="Seed"/>
<Welcome name="Rohit" company="IBM"/>
</div>
)
}
export default App;

__________________________________________________________________________________
React State
-----------
React components has a built-in state object.
Props are used to pass data, whereas state is for managing data
The state object is where you store property values that belongs to the component.
When the state object changes, the component re-renders.
To change a value in the state object, use the this.setState() method.

Creating the state Object


--------------------------
The state object is initialized in the constructor:
class Car extends React.Component {
constructor() {
super();
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
</div>
);
}
}
___________________________________________________________________________________

React Events
------------
In HTML:
<button onclick="clickHandler()">
Clicked
</button>

In React js
<button onClick={clickHandler}>
Clicked
</button>

onmouseover: The mouse is moved over an element


onmouseup: The mouse button is released
onmouseout: The mouse is moved off an element
onmousemove: The mouse is moved
Onmousedown: mouse button is pressed
onload: A image is done loading
onunload: Existing the page
onblur: Losing Focus on element
onchange: Content of a field changes
onclick: Clicking an object
ondblclick: double clicking an object
onfocus element getting a focus
Onkeydown: pushing a keyboard key
Onkeyup: keyboard key is released
Onkeypress: keyboard key is pressed
Onselect: text is selected

Example 1: Call a Function After Clicking a Button


--------------------------------------------------
using class component
---------------------
class ChildComp extends React.Component {
handleClick(){
alert("You clicked button..");
}
render() {
return (
<>
<button onClick={this.handleClick}>Click Me!</button>
</>
)
}
}
export default ChildComp;
using functional component
---------------------------
function App() {

function sayHello() {
alert('Hello!');
}

return (
<button onClick={sayHello}> Click me! </button>
);
}

export default App;

Example 2: Passing argument to the event handler


--------------------------------------------------
There are 2 ways to pass arguments, via the Arrow function() and the Bind method.

class EventComp extends React.Component {


shoot(msg){
alert(msg);
}

render() {
return (
<>
<button onClick={this.shoot.bind(this,"Goal!")}>Take the shot!</button><br/>
<button onClick = {(e) => this.shoot("Goal!",e)}>Take the shot again!</button>
</>
)
}
}
export default EventComp;

Example 3 :Inline functions allow you to write code for event handling directly in
JSX
-----------------------------------------------------------------------------------
------
<button onClick={() => alert("Hello!")}>Say Hello</button>

Rules
React events are named in the format of camelCase
React event handlers are placed inside curly braces Ex onChange={handleSubmit}

Example 4: change state on button click


---------
class EventDemo1 extends React.Component{
constructor(props){
super(props)
this.state = {msg : 'Hello'}//set initial state
}
handleClick(){
this.setState({msg : 'Welcome to the React world!'}) // Changing state
}
render(){
return (
<div>
<h2>Message :</h2><p>{this.state.msg}</p>
<button onClick={this.handleClick.bind(this)}>Click here!</button>
</div>
)
}
}
export default EventDemo1;
___________________________________________________________________________________

React Forms
------------
Handling forms is about how you handle the data when it changes value or gets
submitted.
In HTML, form data is usually handled by the DOM.
In React, form data is usually handled by the components.
When the data is handled by the components, all the data is stored in the component
state.
You can control changes by adding event handlers in the onChange attribute.

class MyForm extends React.Component {


constructor(props) {
super(props);
this.state = {
personName: "",
course:"",
email:""
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event){
alert("form submitted..");
alert(this.state.personName+" "+this.state.course+" "+this.state.email);
}
handleInputChange(event) {
const target = event.target;
this.setState({
[target.name]: target.value
});
}
render() {
return (<>
<form onSubmit={this.handleSubmit} >
<h1>Enquiry Form</h1>
<label>Your Name </label>
<input name="personName" value={this.state.personName}
onChange={this.handleInputChange} />
<br />
<label>Select Course Name</label>
<select name="course" value={this.state.course}
onChange={this.handleInputChange}>
<option>--select--</option>
<option value="C">C</option>
<option value="Java">Java</option>
<option value=".Net">.Net</option>
<option value="Testing">Testing</option>
</select>
<br/>
<label>Email Address</label>
<input name="email" type="text" value={this.state.email}
onChange={this.handleInputChange} />
<br/>
<input type="submit"/>
</form>
<br/><br/>
<fieldset>
<legend>Your Enquiry</legend>
<b>Person Name : {this.state.personName}</b><br/>
<b>Course Name : {this.state.course}</b><br/>
<b>Email : {this.state.email}</b><br/>
</fieldset></>
);
}
}
export default MyForm;

___________________________________________________________________________________
_______
React Routing
1)create a REact Application
create-react-app seed-prj

2)install react-router
seed-prj>npm install react-router-dom@6

3)
**********for bootstrap
npm install bootstrap
npm install jquery popper.js

index.js
import 'bootstrap/dist/css/bootstrap.min.css'
import 'bootstrap/dist/js/bootstrap.bundle.min'
import $ from 'jquery;
import Poppe from 'popper.js;

App.js -->routing metadata


Layout.js---->navigations
create Home.js,AboutUs.js,Contact.js,Enquiry.js,NoPage.js

_________________________________________________________________

Axios
-----
Axios is an HTTP client library based on promises.
It makes sending asynchronous HTTP requests to REST endpoints easier and helps you
perform CRUD operations.

steps:-
1)create a react appln & add axios libraries
create-react-app my-react-prj
my-react-prj>npm install axios
2)import React and Axios so that both can be used in the component. Then you hook
into the componentDidMount lifecycle hook and perform a GET request.

You use axios.get(url) with a URL from an API endpoint to get a promise which
returns a response object. Inside the response object, there is data that is then
assigned the value of person.

PersonList.js
--------------
import axios from "axios";
import React from "react";

export default class PersonList extends React.Component{


state={persons:[]}

componentDidMount(){
axios.get(`http://localhost:5555/emps`).then(
res=>{
const persons=res.data;
this.setState({persons});
}
)
}
render(){
return(<ul>{
this.state.persons.map(
person => <li>{person.id} {person.name}</li>
)
}
</ul>)
}
}

App.js
------
import './App.css';
import PersonList from './PersonList';
function App() {
return (
<div>
<PersonList/>

</div>
);
}
export default App;

_________________________________________________________________________________
Hooks
------
Hooks allow function components to have access to state and other React features.
Because of this, class components are generally no longer needed.
Hooks allow us to "hook" into React features such as state and lifecycle methods.

There are 5 rules for hooks:


Never call Hooks from inside a loop, condition or nested function
Hooks should sit at the top-level of your component
Only call Hooks from React functional components
Never call a Hook from a regular function
Hooks can call other Hooks

Hooks State
------------
Hook state is the new way of declaring a state in React app. Hook uses useState()
functional component for setting and retrieving state. Let us understand Hook state
with the following example.
Example:-
----------
CountApp.js
------------
import React, { useState } from 'react';

function CountApp() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default CountApp;

Hook Effect
-----------
The Effect Hook allows us to perform side effects (an action) in the function
components. It does not use components lifecycle methods which are available in
class components. In other words, Effects Hooks are equivalent to
componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle
methods.

Side effects have common features which the most web applications need to perform,
such as:

Updating the DOM,


Fetching and consuming data from a server API,
Setting up a subscription, etc.
Let us understand Hook Effect with the following example.

import React, { useState, useEffect } from 'react';


function CounterExample() {
const [count, setCount] = useState(0);

// Similar to componentDidMount and componentDidUpdate:


useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default CounterExample;

You might also like