React Basics
React Basics
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
// Traditional way
let a = arr[0];
let b = arr[1];
let c = arr[2];
// Destructuring way
function ParentComponent() {
return (
<div>
</div>
);
}
Child Component
CSIBER
AN AUTONOMOUS INSTITUTE
return (
<div>
<p>Name: {name}</p>
<p>Value: {value}</p>
</div>
);
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
return (
<div>
</div>
);
};
App.js
import './App.css';
function App() {
return (
<div className="App">
<ParentComponent/>
</div>
);
}
Child component getting initial value from
parent component using state
CSIBER
AN AUTONOMOUS INSTITUTE
ChildComponent.js
constructor(props) {
super(props);
this.state = {
value: this.props.initialValue
};
render() {
return (
<div>
</div>
);
}
Defining State in Class
CSIBER
AN AUTONOMOUS INSTITUTE Components
state.js
constructor(){
super()
this.state={
render(){
return <h1>{this.state.msg}</h1>
}
Defining State in Class
CSIBER
AN AUTONOMOUS INSTITUTE Components
app.js
import './App.css';
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
export:
export default:
Using export
File: MyComponents.js
// Named exports
};
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
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
};
};
class MyComponent {
render() {
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
Method 1:
change = () => {
// method logic
};
render() {
return (
);
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Note:
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.
<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",
render(){ }
render() {
return (
<div><h2><font color='maroon'>{this.props.name}</font></h2></div>
render() {
return (
<div>
<h2><font color='blue'>{this.props.designation}</font></h2>
<h2><font color='blue'>{this.props.institute}</font></h2>
</div>
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 './App.css';
function App() {
return (
<div className="App">
<UpdateDatabase/>
</div>
);
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Replace the statement
this.state={
isAdmin:true
this.state={
isAdmin:false
constructor(props){
super(props)
this.state={
isAdmin:true
render() {
return(
StudentList.js
let
↓
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 './App.css';
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
render() {
return (
<ComponentB/>
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
ComponentB.js
render() {
return (
<ComponentC/>
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
}
</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}
import './App.css';
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 './App.css';
function App() {
return (
<div className="App">
<ComponentA/>
</div>
}
Using Destructuring in
CSIBER
AN AUTONOMOUS INSTITUTE Function Parameters
Spread Operator
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
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
SpreadDemo.js
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
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() {
ChildComponent.js
render() {
return (
<div>
</div>
);
constructor(props) {
super(props);
this.state = {
inputValue: '',
};
this.handleInputChange = this.handleInputChange.bind(this);
handleInputChange(event) {
}
More Advanced Example with
CSIBER
AN AUTONOMOUS INSTITUTE
Input Handling
render() {
return (
<div>
</div>
);
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
constructor(props) {
super(props);
this.state = {
value: 42
};
incrementValue = () => {
}
Example
CSIBER
AN AUTONOMOUS INSTITUTE
ChildComponent.js
return (
<div>
<p>Name: {name}</p>
<p>Value: {value}</p>
</div>
);
render() {
return (
<div>
<ChildComponent
name={this.state.name}
value={this.state.value}
setName={this.setName}
incrementValue={this.incrementValue}
/>
</div>
);
• React may batch multiple state updates for performance reasons. This means
• Without prevState, if you try to update the state based on the current state,
When updating state based on the previous state, using prevState ensures you
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
}
Using useState Hook
CSIBER
AN AUTONOMOUS INSTITUTE
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
}
Using useState Hook
CSIBER
AN AUTONOMOUS INSTITUTE
App.js
import './App.css';
function App() {
return (
<div className="App">
<NameComponent/>
</div>
);
setName('Girish'); };
}; }
</div> return (
); <div>
NameComponent.js
function HookCounter2() {
return (
<div>HookCounter2<br></br><br></br>
</div>
}
CSIBER
AN AUTONOMOUS INSTITUTE
App.js
import './App.css';
function App() {
return (
<div className="App">
<HookCounter2/>
</div>
);
App.js
import './App.css';
function App() {
return (
<div className="App">
<NameComponent/>
</div>
);
NameComponent,js
function NameComponent() {
return (
</div>
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
"scripts": {
Example: If you have a server file named server.js, running npm start would execute
npm run dev
CSIBER
AN AUTONOMOUS INSTITUTE
Typical Use Case: This command is used for development purposes, often with features like live
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
"scripts": {
Example: Running npm run dev would execute nodemon server.js, which starts the server and
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
"scripts": {
Example: Running npm run build would execute webpack --mode production, which bundles
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.
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
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
• You define a contextValue object that holds all the values you want to pass through the context.
• The Consumer component receives the context value, which in this case is the object containing
• 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
const contextValue = {
name: "PGN",
age: 25,
isAdmin: true,
};
return (
<MyContext.Provider value={contextValue}>
<ComponentA />
</MyContext.Provider>
);
};
<MyContext.Consumer>
<div>
<h2>Hello {name}</h2>
<p>Age: {age}</p>
</div>
)}
</MyContext.Consumer>
);