[go: up one dir, main page]

0% found this document useful (0 votes)
96 views69 pages

React Complete

The document provides an overview of the Model-View-Controller (MVC) architectural pattern, primarily focusing on the Model component and its application in web and mobile app development. It discusses ReactJS, a JavaScript library for building user interfaces, highlighting its features such as virtual DOM, components, and state management. Additionally, it covers various ES6 features, including arrow functions, destructuring, spread operators, and modules, along with React-specific concepts like props, state, events, and conditional rendering.

Uploaded by

Candy Man
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views69 pages

React Complete

The document provides an overview of the Model-View-Controller (MVC) architectural pattern, primarily focusing on the Model component and its application in web and mobile app development. It discusses ReactJS, a JavaScript library for building user interfaces, highlighting its features such as virtual DOM, components, and state management. Additionally, it covers various ES6 features, including arrow functions, destructuring, spread operators, and modules, along with React-specific concepts like props, state, events, and conditional rendering.

Uploaded by

Candy Man
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

What is a model in an MVC?

• The Model-View-Controller (MVC) is an architectural pattern that


separates an application into three main logical components:
the model, the view, and the controller.
Where is MVC used?
• It was used for desktop graphical user interfaces but nowadays is
used in designing mobile apps and web apps.
ReactJS

• ReactJS is a declarative, efficient, and flexible JavaScript library for


building reusable UI components.
• It is an open-source, component-based front end library which is
responsible only for the view layer of the application.
• It was initially developed and maintained by Facebook and later used
in its products like WhatsApp & Instagram.
Why we use ReactJS?

• The main objective of ReactJS is to develop User Interfaces (UI) that


improves the speed of the apps.
• It uses virtual DOM (JavaScript object), which improves the
performance of the app.
• The JavaScript virtual DOM is faster than the regular DOM.
• It uses component and data patterns that improve readability and
helps to maintain larger apps.
React ES6 Arrow Functions

• Arrow functions were introduced in ES6.


• Arrow functions allow us to write shorter function syntax
Destructuring
❖Destructuring makes it easy to extract only what is needed.
❖Destructuring means to break down a complex structure into simpler
parts.
❖With the syntax of destructuring, you can extract smaller fragments
from objects and arrays. It can be used for assignments and
declaration of a variable.
❖Destructuring is an efficient way to extract multiple values from data
that is stored in arrays or objects. When destructuring an array, we
use their positions (or index) in an assignment.
Example

var arr = ["Hello", "World"]

// destructuring assignment
var [first, second] = arr;

console.log(first); // Hello
console.log(second); // World
Note:
• When destructuring arrays, the order that variables are declared is
important.
• Notice that the object properties do not have to be declared in a
specific order.
React ES6 Spread Operator
• ES6 introduced a new operator referred to as a spread operator,
which consists of three dots (...).
• The JavaScript spread operator (...) allows us to quickly copy all
or part of an existing array or object into another array or
object.
Syntax

• var variablename1 = [...value];

Example
React ES6 Modules

❖JavaScript modules allow you to break up your code


into separate files.
❖This makes it easier to maintain the code-base.
❖ES Modules rely on the import and export statements.
Export

• You can export a function or variable from any file.


• There are two types of exports: Named and Default.
Import

• You can import modules into a file in two ways, based on if they are
named exports or default exports.
• Named exports must be destructured using curly braces. Default
exports do not.
React ES6
• ES6 stands for ECMA Script 6 version
• ECMAScript is the Standardization of Javascript programming
language.
• Use of ES6 features we Write Less and Do More.
React Render HTML

• Render means renew only an appropriate part of information on


user’s screen when the element properties (props) are replaced by
new ones or a component state (as set of props) changes in
application.
• Thanks to the render method, we avoid reloading the whole web
page, save time, and increase productivity.
• React's goal is in many ways to render HTML in a web page.
• React renders HTML to the web page by using a function called
ReactDOM.render().
Packages:

⮚import React from 'react';


⮚import ReactDOM from 'react-dom';
ReactDOM

• The react-dom package provides DOM-specific methods that can be


used at the top level of your app and as an escape hatch to get
outside the React model if you need to.

• import * as ReactDOM from 'react-dom';


React DOM Render
• The purpose of the function is to display the specified HTML code inside
the specified HTML element.
• The Function takes two arguments, HTML code and an HTML element.

For Example:
ReactDOM.render(<p>Welcome</p>,document.getElementById('root'));
React JSX
• JSX Stands for Javascript XML.
• JSX allows us to write HTML in React.
• JSX allows us to write HTML elements in JavaScript and place them in
the DOM without any createElement().
React JSX
• With JSX code vs Without JSX code
• Expression in JSX
• Wrapping elements or children in JSX
• Styling in JSX
• Attributes in JSX
• Comments in JSX
React Components
React Components
• Every application you will develop in React Will be made up of pieces
called components.
• Components make the task of building UIs much easier.
• We have lot of individual components like a Single web page contain
(Search bar,menu bar,nav bar,content,article etc..,)
• Merge all of these individual components to make a parent
components which will be the final UI
Types of Components
• 1)Function Component
• 2)Class Component
Class Component

• A class component must include the extends React.Component


statement.
• This statement creates an inheritance to React.Component, and gives
your component access to React.
• The component also requires a render() method, this method returns
HTML.
Example

class Reactjs extends React.Component {


render() {
return <h2>Hi, I am a React JS!</h2>;
}
}
⮚ Before React 16.8, Class components were the only way to track state and lifecycle on
a React component.
⮚ Function components were considered "state-less".
⮚ With the addition of Hooks, Function components are now almost equivalent to Class
components.
⮚ The differences are so minor that you will probably never need to use a Class
component in React.
⮚ Even though Function components are preferred, there are no current plans on
removing Class components from React.
Difference between class & functional
component
React Props
• Props stand for “Properties.”
• React allows us to pass information to a Component using Props.
• Props are immutable so, we cannot modify the props from inside the
component.
• Props are basically kind of global variable or Object.It is an Object
which stores the value of attributes of a tag and work similar to the
HTML attributes.
• We can access any prop from inside a component’s class
import React from 'react';
import ReactDOM from 'react-dom';

function Laptop(props) {
return <h2>I am a { props.brand }!</h2>;
}

// const myElement = <Laptop brand="Dell" />;


// ReactDOM.render(myElement,document.getElementById('root'));

ReactDOM.render(<Laptop brand="Dell"
/>,document.getElementById('root'));
Pass Data React Props

• Props are also how you pass data from one component to another, as
parameters.
import React from 'react';
import ReactDOM from 'react-dom';

function Student(props) {
return <h2> { props.name }!</h2>;
}

function College() {
return (
<>
<h1>Who Join today in my Whatsapp Group?</h1>
<Student name="vinitha" />
</>
);
}
ReactDOM.render(<College />,document.getElementById('root'));
React State

❖ The state is an updatable structure that is used to contain data or


information about the component.
❖ The state in a component can change over time. The change in state over
time can happen as a response to user action or system event.
❖ It is the heart of the react component which determines the behavior of the
component and how it will render.
❖ It can be set by using the setState() method and calling setState() method
triggers UI updates.
React State
What is the difference between state and props?

❖ props (short for “properties”) and state are both plain JavaScript objects.
❖ While both hold information that influences the output of render, they are
different in one important way:
❖ props get passed to the component (similar to function parameters)
❖ whereas state is managed within the component (similar to variables declared
within a function).
class Reactstate extends React.Component{
constructor()
{
super();
this.state={initalvalue:"Welcome",name:"Guys"}
}
render()
{
return <h1> {this.state.initalvalue} {this.state.name}</h1>
}
}
ReactDOM.render(<Reactstate />,document.getElementById("root"));
class Reactstate extends React.Component{
constructor(){
super();
this.state={initalvalue:"Welcome",name:"Guys"}
}
changevalue = () =>{
this.setState({initalvalue:"Thanks for Watching"})
}
render(){
return <div>
<h1> {this.state.initalvalue} {this.state.name}</h1>
<br/>
<button onClick={this.changevalue} > Exit</button>
</div>
}}
ReactDOM.render(<Reactstate />,document.getElementById("root"));
React Event
❖ An event is an action that could be triggered as a result of the user
action or system generated event
❖ For Example, a mouse click,loading of a web page,pressing a key,
window resizes , and other interactions are calles events.
❖ React events are named using camelCase,rather than lowercase.
❖ In React,with help of JSX you pass a function as the event
handler,rather than a string.
❖ onClick={submit} instead of onclick=”submit()”
import React from 'react';
import ReactDOM from 'react-dom';

function ShowMessage() {
const msg = () => {
alert("Hi all Welcome to ISMUNIV") ;
}

return (
<button onClick={msg}>CLICK!</button>

);
}

ReactDOM.render(<ShowMessage />,document.getElementById('root'));
function ShowMessage() {
const msg = () => {
alert("Hi all Welcome to ISMUNIV") ;
}
const mouseOVer=()=>{
alert("This is MouseOVer");
}
const keyDown=()=>{
alert("This is keyDown");
}
return (
<div>
<button onClick={msg}>CLICK!</button> <br /><br />
<button onMouseOver={mouseOVer}>MouseOver</button><br /><br />
<button onKeyDown={keyDown}>keyDown</button>
</div>
);}
ReactDOM.render(<ShowMessage />,document.getElementById('root'));
React Conditional Rendering

Conditional rendering in React works the same way conditions work in


JavaScript.
There is more than one way to do conditional rendering in React. They are given
below.

● if
● ternary operator
● logical && operator
function Login() {
return <h1>Welcome To Google</h1>;
}
function NewUser() {
return <h1>Plese sign up</h1>;
}
function Signup(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <Login/>;
}
return <NewUser/>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Signup isLoggedIn={true} />);
// index.js
function Temperature(){
return (
<div>
<h1> You Must go hospital</h1>
{
(120 > 103) && alert("High Fever ")
}
</div>
);
}

ReactDOM.render(<Temperature />,document.getElementById('root'));
React Css
★ CSS- Cascading Style Sheet
★ In React we Use to style the React App or Component.
★ Here we are going to discuss mainly three ways to Style react
Components .
1.Inline Styling
2. Css StyleSheet
3. Css Module
Possible Way of Adding CSS to React
Components
Inline Styling:
★ To style an element with the inline style attribute,the value must be
a Javascript object.The Styling must written inside two sets of curly
braces{{}}.
★ If the properties have two names,like background-color,it must be
written in camel case syntax.
CSS Modules:

❖ Css Modules are convenient for components that are placed in


separate files .
❖ The CSS inside a module is available only for the Component that
imported it.
❖ It means any Styling you add can never be applied to other
components without your permission, and you do not have to
worry about name Conflicts
❖ you can create CSS Module with the .module.css extension like a
myStyleSheet.module.css name.
CSS Stylesheets:

You can write your CSS Styling in a separate file,just save


the file with the .css file extension, and import it in Your
application.
React Sass
★ Sass -Syntactically Awesome Stylesheet
★ Sass reduces repetition of css and therefore Saves time.
★ Sass have lot of features that do exist in CSS, like variables,nested
rules,imports,inheritance, built-in functions etc;
★ Install Sass in your React App by running this command in your
terminal
npm install node-sass
★ Sass files has the “.scss” file extension.
★ Sass uses the $ symbol, followed by a name, to declare variables
★ $variablename:value;
React Sass
A browser does not understand Sass code. Therefore, you will need a
Sass pre-processor to convert Sass code into standard CSS. This process
is called transpilling.

Transpilling is a term for taking a source code written in one language


and transform/translate it into another Language.
React Fragments
★ In React, whenever you want to render something on the screen,
,you need to use a render method inside the component
★ The render method will only render a single root node inside it at a
time.
★ However, if you want to return multiple elements, the render
method will require a ‘div’ tag and put the entire content or
elements inside it
★ This extra node to the DOM sometimes results in the wrong
formatting of Your HTML output and its not good semantic html
code.
★ Advantage of using react fragments is it take lesser memory and
quicker execution.
React ES6 Array Methods
❖There are many JavaScript array methods.
❖One of the most useful in React is the .map() array method.
❖The .map() method allows you to run a function on each item in
the array, returning a new array as the result.
React Lists
★ Lists are used to display data in an ordered format and mainly used
to display menus on websites like navigation bar,menu bar etc;
★ Let us now create a list of elements in React.
★ To do this,we will traverse the list using the javascript map()
function and updates elements to be enclosed between <li></li>
elements.
★ Finally we will wrap this new list within <ul></ul> elements and
render it to the DOM.
import React from 'react';
import ReactDOM from 'react-dom';
const newlist = ["HTML","CSS","BOOTSTRAP","JavaScript","React"]
const r1=newlist.map((listvalues)=>
{
return <li>{listvalues}</li>
});
ReactDOM.render(<ul>{r1}</ul>,document.getElementById('root'));
React Keys
★ A “Key” is a special string attribute you need to include when
creating lists of elements in React.
★ Keys are used in React to identify which items in the list are
changed,updated or deleted.In other words we can say that keys
are used to give an identity to the element in the lists.
★ It also helps to determine which components in a collection needs
to be re-rendered instead of re-rendering the entire set of
components every time.
function Menubar(props) //3{
const content=props.data.map((show) => //4
<div key={show.id}>
<h3>{show.id}:{show.title}:{show.content}</h3>
</div>
);
return (<div>
{content}
</div>
);}
const myvalue=[ //1
{id:1,title:'HTML',content:'HyperText Markup'},
{id:2,title:'CSS',content:'Cascading Style Sheet'},];
ReactDOM.render( //2
<Menubar data={myvalue}/>,
document.getElementById('root') //5);
React Forms
★ Forms play a major role in any website for login,signup etc;
★ In React Forms work little different
★ In HTML,form data is usually handled by the DOM.
★ In HTML elements like input tag,the value of the input field changed
whenever the user type.
★ In React,form data is usually handled by the components.
★ But , In React, Whatever the value user types we save it in state and
pass the same value to the input tag as its value,so here its value is
not changed by DOM,it is controlled by react state.
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);
React Hooks
★ React Hooks allows you to use state and other React features
without writing a class.
★ It does not work inside classes. Its work inside the function only
★ Rules of Hooks:
★ 1. Only call Hooks at the top level
★ Do not call Hooks inside loops,conditions, or nested
functions. Hooks should always be used at the top level of the React
functions.
★ 2.Only call Hooks from React functions
★ You cannot call Hooks from regular Javascript
functions.Instead, you can call Hooks from React function
components.Hooks can also be called from custom Hooks.
// Hook with useState
import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function UIL(){
const [subject,setSubject]=useState("HTML")
return(
<>
<h1> User Interface Language is {subject}!</h1>
<button onClick={()=>setSubject("Cascading Style Sheet")}>
CSS
</button>
<button onClick={()=>setSubject("JAVASCRIPT")}>
Javascript
</button>
<button onClick={()=>setSubject("ReactJS")}>
ReactJS
</button>
</> );}
ReactDOM.render(<UIL/>,document.getElementById('root'));
React Hooks State
★ Hook state is the new way of declaring a state in React app.
★ Hooks uses useState() functional Component for setting and
retrieving state.
★ useState is the Hook which needs to call inside a function
component to add some local state to it.
★ The useState returns a pair where the first eleme
React useReducer Hook

❖ The useReducer Hook is similar to the useState Hook.


❖ It allows for custom state logic.
❖ If you find yourself keeping track of multiple pieces of state
that rely on complex logic, useReducer may be useful.
Syntax:
The useReducer Hook accepts two arguments.

useReducer(<reducer>, <initialState>)
React Router
★ ReactJS Router is mainly used for developing Single Page Web
Applications.
★ React Router is used to define multiple routes in the application.
★ When a user types a specific URL into the browser, and if this URL
path matches any 'route' inside the router file, the user will be
redirected to that particular route.
Need of React Router

★ React Router plays an important role to display multiple views in a


single page application.
★ Without React Router, it is not possible to display multiple views in
React applications.
★ Most of the social media websites like Facebook, Instagram uses
React Router for rendering multiple views.

You might also like