0% found this document useful (0 votes)
5 views110 pages

React Basics

This document provides an overview of React.js, focusing on key concepts such as destructuring in JavaScript, component structure, state management, and the differences between named and default exports. It includes examples of how to use destructuring for function parameters and arrays, as well as how to manage state in class components. Additionally, it discusses best practices for handling events and binding methods in React components.

Uploaded by

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

React Basics

This document provides an overview of React.js, focusing on key concepts such as destructuring in JavaScript, component structure, state management, and the differences between named and default exports. It includes examples of how to use destructuring for function parameters and arrays, as well as how to manage state in class components. Additionally, it discusses best practices for handling events and binding methods in React components.

Uploaded by

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

CSIBER

AN AUTONOMOUS INSTITUTE

Basics of React.js

Using React.js
Destructuring Basics
CSIBER
AN AUTONOMOUS INSTITUTE

Destructuring in JavaScript is a convenient way of extracting values from arrays or properties from
objects into distinct variables. This syntax allows for a more concise and readable way of handling arrays
and objects.
Object Destructuring
With object destructuring, you can extract properties from objects and assign them to variables:
// Traditional way
let obj = { name: "Alice", age: 25 };
let name = obj.name;
let age = obj.age;

// Destructuring way
let { name, age } = obj //No. of variables should be equal to no. of properties of obj.
You can also rename variables:
Destructuring Basics
CSIBER
AN AUTONOMOUS INSTITUTE

You can also rename variables:


let { name: userName, age: userAge } = { name: "Alice", age: 25 };
// userName = "Alice", userAge = 25\
And assign default values:
let { name, age, country = "USA" } = { name: "Alice", age: 25 };
// name = "Alice", age = 25, country = "USA“
Note:
Exact Match: If you destructure without renaming, the variable names must match
the keys in the object.
Renaming: If you rename the variables during destructuring, the new variable names
do not need to match the keys in the object.
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Destructuring can be used in function parameters to directly extract
values:
function greet({ name, age }) {
console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}
greet({ name: "Alice", age: 25 });
OR
obj=({ name: "Alice", age: 25 };
greet(obj);
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Arrays
Array DestructuringWith array destructuring, you can extract values from arrays and

assign them to variables in a single statement:

// Traditional way

let arr = [1, 2, 3];

let a = arr[0];

let b = arr[1];

let c = arr[2];

// Destructuring way

let [a, b, c] = [1, 2, 3];


Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Arrays
You can also skip elements:
let [a, , c] = [1, 2, 3]; // a = 1, c = 3
And assign default values:
let [a = 5, b = 7] = [1]; // a = 1, b = 7
Parent Component
CSIBER
AN AUTONOMOUS INSTITUTE

import React from 'react';

import ChildComponent from './ChildComponent';

function ParentComponent() {

const name = "John Doe";

const value = 42;

return (

<div>

<ChildComponent name={name} value={value} />

</div>

);

}
Child Component
CSIBER
AN AUTONOMOUS INSTITUTE

import React from 'react';

function ChildComponent({ name, value }) {

return (

<div>

<p>Name: {name}</p>

<p>Value: {value}</p>

</div>

);

export default ChildComponent;


Child component getting initial value from
parent component using props
CSIBER
AN AUTONOMOUS INSTITUTE

ChildComponent.js

import React from 'react';
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.initialValue
};
}
render() {
const { value } = this.state;
return (
<div>
<p>Initial Value: {value}</p>
</div>
);
}
}
export default ChildComponent;
Child component getting initial value from
parent component using props
CSIBER
AN AUTONOMOUS INSTITUTE

ParentComponent.js

import React from 'react';

import ChildComponent from './ChildComponent';

const ParentComponent = () => {

const initialValue = 'Hello, World!';

return (

<div>

<ChildComponent initialValue={initialValue} />

</div>

);

};

export default ParentComponent;


Child component getting initial value from
parent component using props
CSIBER
AN AUTONOMOUS INSTITUTE

App.js

import './App.css';

import ParentComponent from './components/ParentComponent';

function App() {

return (

<div className="App">

<ParentComponent/>

</div>

);

}
Child component getting initial value from
parent component using state
CSIBER
AN AUTONOMOUS INSTITUTE

ChildComponent.js

import React from 'react';

class ChildComponent extends React.Component {

constructor(props) {

super(props);

this.state = {

value: this.props.initialValue

};

render() {

const { value } = this.state;

return (

<div>

<p><font color='red'>Initial Value: {value}</font></p>

</div>

);

}
Defining State in Class
CSIBER
AN AUTONOMOUS INSTITUTE Components
state.js

import {Component} from 'react'

class State extends Component{

constructor(){

super()

this.state={

msg : "React.js is interesting"

render(){

return <h1>{this.state.msg}</h1>

}
Defining State in Class
CSIBER
AN AUTONOMOUS INSTITUTE Components
app.js

import logo from './logo.svg';

import './App.css';

import State from './components/state';

function App() {

return (

<div className="App">

<State/>

</div>

);

}
Named Exports
CSIBER
AN AUTONOMOUS INSTITUTE export Vs. export default
In React (and JavaScript in general), the export and export default statements are used to export functions,

objects, or primitives from a module so that they can be used in other modules with the import statement. Here

are the key differences:

export:

• Used to export multiple values from a module.

• Each export must be imported with the same name.

• You can have multiple named exports per module.

• Curly brackets are used for importing the module.

export default:

• Used to export a single value from a module.

• The exported value can be imported with any name.

• Only one default export is allowed per module.


Example
CSIBER
AN AUTONOMOUS INSTITUTE

Using export

File: MyComponents.js

// Named exports

export const Header = () => {

return <h1>This is the Header</h1>;

};

export const Footer = () => {

return <h1>This is the Footer</h1>;


Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
File: App.js

import React from 'react';

// Import named exports

import { Header, Footer } from './MyComponents';

const App = () => {

return (

<div>

<Header />

<Footer />

</div>

);

};
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Using export default
File: Header.js
// Default export
const Header = () => {
return <h1>This is the Header</h1>;
};
export default Header;
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
File: Footer.js
// Default export
const Footer = () => {
return <h1>This is the Footer</h1>;
};
export default Footer;
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
File: App.js

import React from 'react';

// Import default exports

import Header from './Header';

import Footer from './Footer';

const App = () => {

return (

<div>

<Header />

<Footer />

</div>

);

};
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Note:
• Use export when you want to export multiple named values
from a module. They must be imported using their exact
names.
• Use export default when you want to export a single value
from a module. It can be imported using any name.
Multiple Exports
CSIBER
AN AUTONOMOUS INSTITUTE

Using export { … } you can export multiple components from a single file using named exports. Here's

how you can do it:

// Define Header component

const Header = () => {

return <h1>This is the Header</h1>;

};

// Define Footer component

const Footer = () => {

return <h1>This is the Footer</h1>;

};

// Export both components

export { Header, Footer };


Importing a Component
CSIBER
AN AUTONOMOUS INSTITUTE Using Different Name
MyComponent.js

// Define a class component

class MyComponent {

render() {

return <h1>This is My Component</h1>;

// Export the class as the default export

export default MyComponent;


Importing a Component
CSIBER
AN AUTONOMOUS INSTITUTE Using Different Name
App.js

import React from 'react';

// Import the default export and rename it

import RenamedComponent from './MyComponent';

const App = () => {

return (

<div>

<RenamedComponent />

</div>

);

};
Changing the State on Click of a
CSIBER Button (Using Arrow Function)
AN AUTONOMOUS INSTITUTE
state.js

import {Component} from 'react'
class State extends Component{
constructor(){
super()
this.state={
msg : "React.js is interesting"
}
}
change(){
this.setState({
msg:"React.js is used for designing stunning user interfaces"
})
}
render(){
return (
<div>
<h1>{this.state.msg}</h1>
<button onClick={()=>this.change()} >Change Message</button>
</div>
)
}
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters

Click on ‘Change Message’ button which changes the state variable


‘msg’ and the text displayed on the browser window will accordingly
change.
Using Arrow Function in
CSIBER
AN AUTONOMOUS INSTITUTE
onClick

Method 1:

Using an arrow function in the onClick attribute.

<button onClick={() => this.change()} >Change


Message</button>

Method 2:Passing the function directly to the onClick attribute

<button onClick={this.change} >Change Message</button>


Using Arrow Function in
CSIBER
AN AUTONOMOUS INSTITUTE
onClick
When to Use Arrow Function
1. When you need to pass arguments to the function:If change takes
parameters, you need to use an arrow function to pass them:
<button onClick={() => this.change(param1, param2)} >Change
Message</button>
2. When you want to bind the context (this) explicitly
This ensures that this inside the change method refers to the
current component instance.
Using Arrow Function in
CSIBER
AN AUTONOMOUS INSTITUTE
onClick
Pros and Cons
Pros:
Can pass arguments to the function. Automatically binds this to the
component instance.
Cons:
Creates a new function on every render, which could potentially
affect performance if the component re-renders frequently.
Using Arrow Function in
CSIBER
AN AUTONOMOUS INSTITUTE
onClick
Passing the Function Directly
<button onClick={this.change} >Change Message</button>
When to Use:
When the function does not take any arguments and the context of this is
correctly bound.
Pros:
Does not create a new function on every render, which can be more performant.
Cons:
If this.change is not properly bound to the component instance, this inside
change might be undefined.
Using Arrow Function in
CSIBER
AN AUTONOMOUS INSTITUTE
onClick
Binding Methods in Class Components
In class components, to ensure that this refers to the component instance, you often need to bind methods in the constructor.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.change = this.change.bind(this);
}
change() {
// method logic
}
render() {
return (
<button onClick={this.change} >Change Message</button>
);
}
}
Using Arrow Function in
CSIBER
AN AUTONOMOUS INSTITUTE
onClick
Alternatively, you can use class fields to define methods

class MyComponent extends React.Component {

change = () => {

// method logic

};

render() {

return (

<button onClick={this.change} >Change Message</button>

);

}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Note:

<button onClick={this.change}>Change Message</button>

This option correctly assigns the this.change method as the onClick event
handler. When the button is clicked, the this.change method will be called.

<button onClick={this.change()}>Change Message</button>

This option invokes the this.change method immediately when the


component renders because it includes parentheses () after this.change. As
a result, the this.change method will be called during rendering and not
when the button is clicked. This is likely not the desired behaviour.
Combining State and Props
CSIBER
AN AUTONOMOUS INSTITUTE

<div>
App.js
<div>

<h1><font color='green'>Profile : </font></h1>
import React, { Component } from 'react';
<FirstComponent name={this.state.name}/>
import FirstComponent from './components/FirstComponent';
<SecondComponent designation={this.state.designation}
import SecondComponent from './components/SecondComponent';
institute={this.state.institute}/>
class App extends Component{
</div>
constructor(props) {
</div>
super(props)
);
this.state = {
}
name : "Dr. Poornima G. Naik", }
designation : "HOD, Department of Computer Studied", App.defaultProps = {
institute: "CSIBER, Kolhapur", name : "Dr. Poornima G. Naik",
} designation : "HOD, Department of Computer Studied",

} institute: "CSIBER, Kolhapur",

render(){ }

return ( export default App;


Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
FirstComponent.js

import React, { Component } from 'react'

export class FirstComponent extends Component {

render() {

return (

<div><h2><font color='maroon'>{this.props.name}</font></h2></div>

export default FirstComponent


Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
SecondComponent.js

import React, { Component } from 'react'

export class SecondComponent extends Component {

render() {

return (

<div>

<h2><font color='blue'>{this.props.designation}</font></h2>

<h2><font color='blue'>{this.props.institute}</font></h2>

</div>

export default SecondComponent


Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
JSX Elements
CSIBER
AN AUTONOMOUS INSTITUTE

In JSX, there is a subtle but important difference between


msg=<h1>Hello</h1> and
msg="<h1>Hello</h1>"
msg=<h1>Hello</h1>
This is JSX syntax where you are assigning a JSX element to the msg
variable. msg will hold a React element that can be rendered by React.
Example usage:
const msg = <h1>Hello</h1>;
JSX Elements
CSIBER
AN AUTONOMOUS INSTITUTE

When used inside a React component, this can be rendered directly.


function App() {
const msg = <h1>Hello</h1>;
return (
<div>
{msg}
</div>
);
}
JSX Elements
CSIBER
AN AUTONOMOUS INSTITUTE

msg="<h1>Hello</h1>“
This is assigning a string to the msg variable. msg will hold a plain
string containing HTML markup.
Example usage:
const msg = "<h1>Hello</h1>";
Exploring Conditional
CSIBER
AN AUTONOMOUS INSTITUTE Rendering in React
JSX rendered in React.js can be customized using conditional
rendering employing one of the four methods described below:
• Using if..else statement
• Using element variables
• Using ternary conditional operator.
• Using short-circuit operator.
Method 1: Using if..else
CSIBER
AN AUTONOMOUS INSTITUTE Statement
conditional.js

import React, { Component } from 'react';
class UpdateDatabase extends Component {
constructor(props){
super(props)
this.state={
isAdmin:true
}
}
render() {
if (this.state.isAdmin){
return (
<div><h2>You have permissions to update database</h2></div>
)
}
else{
return (
<div><h2>You do not have permissions to update database</h2></div>
)
}
}
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
App.js

import logo from './logo.svg';

import './App.css';

import UpdateDatabase from './components/conditional';

function App() {

return (

<div className="App">

<UpdateDatabase/>

</div>

);

}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Replace the statement

this.state={

isAdmin:true

with the one shown below

this.state={

isAdmin:false

and re-execute the application.


Method 2: Using Element
CSIBER
AN AUTONOMOUS INSTITUTE Variables
conditional.js

import React, { Component } from 'react';
class UpdateDatabase extends Component {
constructor(props){
super(props)
this.state={
isAdmin:true
}
}
render() {
let msg
if (this.state.isAdmin){
msg=<div><h2>You have previledges to update database</h2></div>
}
else{
msg=<div><h2>You do not have previledges to update database</h2></div>
}
return <div>{msg}</div>
}
}
Method 3: Using Ternary
CSIBER
AN AUTONOMOUS INSTITUTE Conditional Operator
conditional.js

import React, { Component } from 'react';
class UpdateDatabase extends Component {
constructor(props){
super(props)
this.state={
isAdmin:true
}
}
render() {
return(
this.state.isAdmin?
<div><h2><font color='blue'>You have previledges to update
database</font></h2></div>:
<div><h2><font color='red'>You do not have previledges to update
database</font></h2></div>
)
}
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Method 4: Using Short
CSIBER
AN AUTONOMOUS INSTITUTE Circuit Operator
import React, { Component } from 'react';

class UpdateDatabase extends Component {

constructor(props){

super(props)

this.state={

isAdmin:true

render() {

return(

this.state.isAdmin && <div><h2><font color='green'>You have previledges to update database</font></h2></div>

export default UpdateDatabase;


List Rendering
CSIBER
AN AUTONOMOUS INSTITUTE

StudentList.js
let

import React from 'react'; studentList=students.map(student=><div><h2><font


function StudentList() {

let students=[
color='blue'>My name is {student.name}
{
and my rollno is {student.rollno}</font></h2></div>)
rollno:1,

name:"Maya" return (
},

{
<div>
rollno:2,
{
name:"Milan"

}, studentList
{

rollno:3, }
name:"Ashok"
</div>
},

{
);
rollno:4,

name:"Sachin" }
}
List Rendering
CSIBER
AN AUTONOMOUS INSTITUTE

app.js

import logo from './logo.svg';

import './App.css';

import StudentList from './components/StudentList'

function App() {

return (

<div className="App">

<StudentList/>

</div>

}
Exploring Context in
CSIBER
AN AUTONOMOUS INSTITUTE React.js
Contexts enable passing of data through the component tree
without the need to pass props down manually through each
level.
Need for Context
Example:
CSIBER
AN AUTONOMOUS INSTITUTE

The following example demonstrates using the context for sharing


value between different components of an application.
Create the following three components in ‘components’ folder.
ComponentA contains ComponentB and ComponentB contains
App ComponentA
ComponentC.
ComponentB

‘name’ prop using


Context API ComponentC

Component C is a prop consumer and App is a Provider.


Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
ComponentA.js

import React, { Component } from 'react'

import ComponentB from './ComponentB'

export class ComponentA extends Component {

render() {

return (

<ComponentB/>

}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
ComponentB.js

import React, { Component } from 'react'

import ComponentC from './ComponentC'

export class ComponentB extends Component {

render() {

return (

<ComponentC/>

export default ComponentB


Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
ComponentC.js Consumer Component

The Consumer component is part of the React Context API. It subscribes to
import React, { Component } from 'react'
the nearest Provider above it in the component tree and gets the current
import {Consumer} from './Context1'
value from that Provider.
export class ComponentC extends Component {

render() { Function as a Child Pattern

return ( The Consumer expects a function as its child. This is a special pattern in
<Consumer> React known as the “Function as a Child” or “Render Prop” pattern.
{
Automatic Invocation
name => {
When the Consumer component is rendered, React automatically calls the
return <h2> Hello {name}</h2>
function provided as its child. The current context value is passed as an
}

} argument to this function.

</Consumer> Rendering
)
The function returns a React element (in this case, <h2> Hello
}
{name}</h2>), which React then renders.
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Context1.js

import React from 'react'
const context=React.createContext()
const Provider=context.Provider
const Consumer=context.Consumer
export {Provider, Consumer}

Note: ComponentC imports Consumer and


App imports Provider.
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
App.js

import logo from './logo.svg';

import './App.css';

import ComponentA from './components/ComponentA';

import {Provider} from './components//Context1'

function App() {

return (

<div className="App">

<Provider value="PGN">

<ComponentA/>

</Provider>

</div>

}
Workflow of Application
CSIBER
AN AUTONOMOUS INSTITUTE
Setting Default Value for
CSIBER
AN AUTONOMOUS INSTITUTE Context
Context1.js

import React from 'react'
const context=React.createContext('CSIBER')
const Provider=context.Provider
const Consumer=context.Consumer
export {Provider, Consumer}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
With the default value in place there is no need of <Provider>
element in App Component. If the <Provider> tag is inserted it
will consume the value provided by the provider. Hence if
<provider> tag is missing then default value will be consumed.
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
App.js

import logo from './logo.svg';

import './App.css';

import ComponentA from './components/ComponentA';

import {Provider} from './components//Context1'

function App() {

return (

<div className="App">

<ComponentA/>

</div>

}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Spread Operator
CSIBER
AN AUTONOMOUS INSTITUTE

The spread operator (...) in JavaScript allows you to spread out


elements of an iterable (like an array or an object) into individual
elements. It is a powerful feature that simplifies working with
collections of data and helps in writing more concise and
readable code.
Usage with Arrays
CSIBER
AN AUTONOMOUS INSTITUTE

1. Copying Arrays
The spread operator can be used to create a shallow copy of an
array.
Program:
const originalArray = [1, 2, 3];
const copyArray = [...originalArray];
console.log(copyArray); // Output: [1, 2, 3]
Usage with Arrays
CSIBER
AN AUTONOMOUS INSTITUTE

2. Merging Arrays
You can merge multiple arrays into one.
Program:
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const mergedArray = [...array1, ...array2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
Usage with Arrays
CSIBER
AN AUTONOMOUS INSTITUTE

3. Adding Elements to an Array


You can add new elements to an array.
Program:
const array = [1, 2, 3];
const newArray = [0, ...array, 4];
console.log(newArray); // Output: [0, 1, 2, 3, 4]
Usage with Objects
CSIBER
AN AUTONOMOUS INSTITUTE

1. Copying Objects
The spread operator can be used to create a shallow copy of an
object.
Program:
const originalObject = { a: 1, b: 2 };
const copyObject = { ...originalObject };
console.log(copyObject); // Output: { a: 1, b: 2 }
Usage with Objects
CSIBER
AN AUTONOMOUS INSTITUTE

2. Merging Objects
You can merge multiple objects into one.
Program:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObject = { ...obj1, ...obj2 };
console.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }
Usage with Objects
CSIBER
AN AUTONOMOUS INSTITUTE

3. Adding/Updating Properties in an Object


You can add new properties or update existing properties in an
object.
Program:
const obj = { a: 1, b: 2 };
const newObj = { ...obj, b: 3, c: 4 };
console.log(newObj); // Output: { a: 1, b: 3, c: 4 }
Function Arguments
CSIBER
AN AUTONOMOUS INSTITUTE

Expanding Elements in Function Calls


The spread operator can be used to expand elements of an array
as arguments to a function.
Program:
const numbers = [1, 2, 3];
const sum = (a, b, c) => a + b + c;
console.log(sum(...numbers)); // Output: 6
Array Spreading Using
CSIBER
AN AUTONOMOUS INSTITUTE Spread Operator
SpreadDemo.js

const arr = [1, 2, 3];
const newArr = [...arr, 4, 5, 6];
console.log(newArr);
Object Spreading Using
CSIBER
AN AUTONOMOUS INSTITUTE
Spread Operator
SpreadDemo.js

const student = { rollno: 1, name: "Maya" };
const newStudent = { ...student, city:"Kolhapur",state:"MH" };
console.log(newStudent);
Modifying the Existing Properties of
CSIBER the Object Using Spread Operator
AN AUTONOMOUS INSTITUTE

SpreadDemo.js

const student = { rollno: 1, name: "Maya" };

const newStudent = { ...student, city:"Kolhapur",state:"MH" };

const oldStudent ={...student,name:"Milan"}

console.log(newStudent)

console.log(oldStudent);
String Spreading Using Spread
CSIBER
AN AUTONOMOUS INSTITUTE
Operator
SpreadDemo.js

const institute=”SIBER”
const chars={..institute}
console.log(chars);
Using Spread Operator in
CSIBER
AN AUTONOMOUS INSTITUTE Function Arguments
SpreadDemo.js

function add(x, y, z) {
return x + y + z;
}
const nums = [1, 2, 3];
const sum = add(...nums);
console.log("Sum",sum);
Passing Function as prop
CSIBER
AN AUTONOMOUS INSTITUTE

In React, functions can be passed as props to components. This is


a common pattern for handling events, updating state, and
enabling communication between components. When you pass
a function as a prop, the child component can call this function
to perform some action, often involving updating the state or
triggering side effects in the parent component.
Passing Function as prop
CSIBER
AN AUTONOMOUS INSTITUTE

App.js render() {
↓ return (
import React, { Component } from 'react'; <div>
import ChildComponent from './ChildComponent'; <h1>{this.state.message}</h1>
class App extends Component { <ChildComponent onButtonClick={this.handleClick} />
constructor(props) { </div>
super(props); );
this.state = { }
message: 'Hello from parent',
}
};
export default App;
// Binding the handleClick method to the class instance

this.handleClick = this.handleClick.bind(this);

handleClick() {

this.setState({ message: 'Message updated by child' });


Passing Function as prop
CSIBER
AN AUTONOMOUS INSTITUTE

ChildComponent.js

import React, { Component } from 'react';

class ChildComponent extends Component {

render() {

return (

<div>

<button onClick={this.props.onButtonClick}>Click me to update message</button>

</div>

);

export default ChildComponent;


More Advanced Example with
CSIBER
AN AUTONOMOUS INSTITUTE
Input Handling
App.js

import React, { Component } from 'react';

import InputComponent from './InputComponent';

class App extends Component {

constructor(props) {

super(props);

this.state = {

inputValue: '',

};

// Binding the handleInputChange method to the class instance

this.handleInputChange = this.handleInputChange.bind(this);

handleInputChange(event) {

this.setState({ inputValue: event.target.value });

}
More Advanced Example with
CSIBER
AN AUTONOMOUS INSTITUTE
Input Handling
render() {

return (

<div>

<h1>Current Input: {this.state.inputValue}</h1>

<InputComponent onInputChange={this.handleInputChange} />

</div>

);

export default App;


More Advanced Example with
AN AUTONOMOUS INSTITUTE
CSIBER Input Handling
InputComponent.js

import React, { Component } from 'react';

class InputComponent extends Component {

render() {

return (

<div>

<input

type="text"

onChange={this.props.onInputChange}

placeholder="Type something"

/>

</div>

);

}
Example
CSIBER Significance of Previous State
AN AUTONOMOUS INSTITUTE

ParentComponent.js

import React, { Component } from 'react';

import ChildComponent from './ChildComponent';

class ParentComponent extends Component {

constructor(props) {

super(props);

this.state = {

name: "John Doe",

value: 42

};

setName = (newName) => {

this.setState({ name: newName });

incrementValue = () => {

this.setState((prevState) => ({ value: prevState.value + 1 }));

}
Example
CSIBER
AN AUTONOMOUS INSTITUTE

ChildComponent.js

import React from 'react';

function ChildComponent({ name, value, setName, incrementValue }) {

return (

<div>

<p>Name: {name}</p>

<p>Value: {value}</p>

<button onClick={() => setName("Jane Smith")}>Change Name</button>

<button onClick={incrementValue}>Increment Value</button>

</div>

);

export default ChildComponent;


Example
CSIBER
AN AUTONOMOUS INSTITUTE

render() {

return (

<div>

<ChildComponent

name={this.state.name}

value={this.state.value}

setName={this.setName}

incrementValue={this.incrementValue}

/>

<button onClick={() => this.setName("Jane Smith")}>Change Name</button>

<button onClick={this.incrementValue}>Increment Value</button>

</div>

);

export default ParentComponent;


Exploring Previous State
CSIBER
AN AUTONOMOUS INSTITUTE

The prevState parameter in the this.setState() function is used to

access the previous state values in class components. This is

important when the new state depends on the previous state.

Without prevState, you might encounter issues due to the

asynchronous nature of setState, leading to potential

inconsistencies or unexpected behavior.


Significance of Previous State
CSIBER
AN AUTONOMOUS INSTITUTE

Why prevState is Important

• Asynchronous Nature of setState

• React may batch multiple state updates for performance reasons. This means

that state updates are not guaranteed to be applied immediately.

• Without prevState, if you try to update the state based on the current state,

you might end up with outdated or incorrect state values.

Updating State Based on Previous State:

When updating state based on the previous state, using prevState ensures you

have the most recent state, preventing race conditions.


Example Without prevState
CSIBER
AN AUTONOMOUS INSTITUTE

import React, { Component } from 'react'; render() {


import ChildComponent from './ChildComponent'; return (
class ParentComponent extends Component {
<div>
constructor(props) {
<ChildComponent
super(props);
value={this.state.value}
this.state = {
incrementValue={this.incrementValue}
value: 0
/>
};
</div>
}
);
incrementValue = () => {

// Incorrect way: might lead to unexpected behavior }

this.setState({ value: this.state.value + 1 }); }

} export default ParentComponent;


Example With prevState
CSIBER
AN AUTONOMOUS INSTITUTE

import React, { Component } from 'react'; render() {

return (
import ChildComponent from './ChildComponent';
<div>
class ParentComponent extends Component {
<ChildComponent
constructor(props) {
value={this.state.value}
super(props); incrementValue={this.incrementValue}

this.state = { />

value: 0 </div>

);
};
}
}
}
incrementValue = () => {
export default ParentComponent;
// Correct way: ensures you get the latest state

this.setState((prevState) => ({ value: prevState.value + 1 }));

}
Using useState Hook
CSIBER
AN AUTONOMOUS INSTITUTE

this.setState((prevState) => ({ value: prevState.value + 1 }));

The parentheses () are used to immediately return an object from the arrow
function. Without these parentheses, JavaScript would interpret the curly
braces {} as the start of a function body, not an object.

The arrow function is invoked by React's setState internally, not directly in the
code. React calls this function with the previous state to compute the new
state.

setState Implementation: React calls the provided function with the current
state (prevState) and props. The function's return value is then used to update
the component's state.
Using useState Hook
CSIBER
AN AUTONOMOUS INSTITUTE

this.setState((prevState) => ({ value: prevState.value + 1 }));

In the above arrow function, the return statement is implicit. This is


a feature of JavaScript arrow functions that allows for a more concise
syntax when the function body consists of a single expression.

Arrow Function with Implicit Return

An arrow function with a single expression does not need an explicit


return statement. The expression's result is automatically returned
Using useState Hook
CSIBER
AN AUTONOMOUS INSTITUTE

import React, { Component } from 'react';


NameComponent.js
class NameComponent extends Component {

constructor(props) {
import React, { useState } from 'react'
super(props);
function NameComponent () {
this.state = {
const [name, setName] = useState('Poornima')
name: 'Poornima'
return <h1> My name is {name} </h1>
};
} }
export default NameComponent render() {

return <h1>My name is {this.state.name}</h1>;

}
Using useState Hook
CSIBER
AN AUTONOMOUS INSTITUTE

App.js

import './App.css';

import NameComponent from './components/NameComponent';

function App() {

return (

<div className="App">

<NameComponent/>

</div>

);

export default App;


Using useState Hook
CSIBER
AN AUTONOMOUS INSTITUTE
Updating using useState
CSIBER
AN AUTONOMOUS INSTITUTE

NameComponent.js import React, { Component } from 'react';

↓ class NameComponent extends Component {

import React, { useState } from 'react'; constructor(props) {

function NameComponent() { super(props);

const [name, setName] = useState('Poornima'); this.state = {

const updateName = () => { name: 'Poornima'

setName('Girish'); };

}; }

return ( updateName = () => {

<div> this.setState({ name: 'Girish' });

<h1>My name is {name}</h1> }

<button onClick={updateName}>Update Name</button> render() {

</div> return (

); <div>

} <h1>My name is {this.state.name}</h1>

export default NameComponent; <button onClick={this.updateName}>Update Name</button>

</div> );}} export default NameComponent;


Updating using useState
CSIBER
AN AUTONOMOUS INSTITUTE
Using Object as a State
CSIBER Variable with useState Hook
AN AUTONOMOUS INSTITUTE

NameComponent.js

import React, {useState} from 'react'

function HookCounter2() {

const [name,setName] = useState({firstName:'', lastName:''})

return (

<div>HookCounter2<br></br><br></br>

<input type="text" value={name.firstName} onChange={e=>setName({firstName:e.target.value})}></input>

<input type="text" value={name.lastName} onChange={e=>setName({lastName:e.target.value})}></input>

<h2>First Name : {name.firstName}</h2>

<h2>Last Name : {name.lastName}</h2>

</div>

}
CSIBER
AN AUTONOMOUS INSTITUTE

App.js

import './App.css';

import HookCounter2 from './components/HookCounter2';

function App() {

return (

<div className="App">

<HookCounter2/>

</div>

);

export default App;


CSIBER
AN AUTONOMOUS INSTITUTE
CSIBER
AN AUTONOMOUS INSTITUTE

App.js

import './App.css';

import NameComponent from './components/NameComponent';

function App() {

return (

<div className="App">

<NameComponent/>

</div>

);

export default App;


Updating NameComponent
CSIBER
AN AUTONOMOUS INSTITUTE

NameComponent,js

import React, {useState} from 'react'

function NameComponent() {

const [name,setName] = useState({firstName:'', lastName:''})

return (

<div><h2><font color="orange">Name Component</font></h2>

<input type="text" value={name.firstName} onChange={e=>setName({...name,firstName:e.target.value})}></input>

<input type="text" value={name.lastName} onChange={e=>setName({...name,lastName:e.target.value})}></input>

<h2>First Name : {name.firstName}</h2>

<h2>Last Name : {name.lastName}</h2>

</div>

export default NameComponent


CSIBER
AN AUTONOMOUS INSTITUTE
npm start
CSIBER
AN AUTONOMOUS INSTITUTE

Purpose: Starts the application.

Typical Use Case: This command is used to run your application in a production-like

environment.

Configuration: In the package.json file, the start script is usually defined to run the

main entry point of your application. For example:

"scripts": {

"start": "node server.js"

Example: If you have a server file named server.js, running npm start would execute
npm run dev
CSIBER
AN AUTONOMOUS INSTITUTE

Purpose: Runs the application in development mode.

Typical Use Case: This command is used for development purposes, often with features like live

reloading or hot module replacement to improve the development workflow.

Configuration: In the package.json file, the dev script is usually defined to start a development

server or run the application with a tool like nodemon (which watches for file changes and

restarts the server). For example:

"scripts": {

"dev": "nodemon server.js"

Example: Running npm run dev would execute nodemon server.js, which starts the server and

restarts it whenever changes are detected.


npm run build
CSIBER
AN AUTONOMOUS INSTITUTE

Purpose: Creates a production build of the application.

Typical Use Case: This command is used to compile and bundle the application for deployment.

It usually involves minifying code, optimizing assets, and preparing the application for a

production environment.

Configuration: In the package.json file, the build script is usually defined to run build tools or

commands specific to your project's build process. For example:

"scripts": {

"build": "webpack --mode production"

Example: Running npm run build would execute webpack --mode production, which bundles

and optimizes the application for production.


npm run build
CSIBER
AN AUTONOMOUS INSTITUTE

npm start: Starts the application, usually in a production environment.

npm run dev: Starts the application in development mode, often with

live reloading.

npm run build: Compiles and bundles the application for production

deployment.
React’s Context API
CSIBER
AN AUTONOMOUS INSTITUTE

Key Points:

Single value Prop: The Provider component only takes a value prop.

Object Structure: To pass multiple values, you can use an object.

When using React's Context API, the Provider component indeed only

accepts a single prop called value, which is used to pass data down to

consuming components. However, you can structure this value prop to

hold multiple pieces of information by using an object or other data

structures.
Providing Multiple Values
CSIBER
AN AUTONOMOUS INSTITUTE

1. Creating a Context: You create a context object using React.createContext(). This will be used to provide

and consume the context values.

2. Providing Multiple Values:

• You define a contextValue object that holds all the values you want to pass through the context.

• This object is then passed to the Provider component's value prop.

3. Consuming Multiple Values:

• The Consumer component receives the context value, which in this case is the object containing

name, age, and isAdmin.

• You can destructure this object in the function passed to the Consumer to access and use these values

in your component.

This approach allows you to pass any number of values through the context by including them in the

object provided to the Provider component.


Providing Multiple Values
CSIBER
AN AUTONOMOUS INSTITUTE

Step 1: Create a Context

import React from 'react';

const MyContext = React.createContext();

export default MyContext;


Providing Multiple Values
CSIBER
AN AUTONOMOUS INSTITUTE

Step 2: Provide Multiple Values:

import React from 'react';

import MyContext from './MyContext';

const App = () => {

const contextValue = {

name: "PGN",

age: 25,

isAdmin: true,

};

return (

<MyContext.Provider value={contextValue}>

<ComponentA />

</MyContext.Provider>

);

};

export default App;


Providing Multiple Values
CSIBER
AN AUTONOMOUS INSTITUTE

Step 3: Consume Multiple Values:

import React from 'react';

import MyContext from './MyContext';

const ComponentA = () => (

<MyContext.Consumer>

{({ name, age, isAdmin }) => (

<div>

<h2>Hello {name}</h2>

<p>Age: {age}</p>

<p>Admin: {isAdmin ? "Yes" : "No"}</p>

</div>

)}

</MyContext.Consumer>

);

export default ComponentA;

You might also like