WDF Unit 3 and 4 PDF
WDF Unit 3 and 4 PDF
React, components are the building blocks of a user interface. They are reusable,
self-contained pieces of code that represent a part of the UI. React allows you to
break down your UI into smaller components, which makes it easier to manage and
maintain your codebase.
Function Components: These are simple JavaScript functions that take props as
input and return JSX elements. They are often used for presentational or stateless
components.
Example
function FunctionComponent(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
};
return (
<div>
<p>Count: {count}</p>
</div>
);
};
Class Components: These are ES6 classes that extend from React.Component or
React.PureComponent. They have a render() method where you define the
structure of your component's UI using JSX. Class components are used for
components that need to manage state or have lifecycle methods.
Example
constructor(props) {
super(props);
this.state = {
count: 0
};
componentDidMount() {
handleClick = () => {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick}>Increment</button>
</div>
);
https://www.geeksforgeeks.org/reactjs-lifecycle-components/
The React lifecycle refers to the different phases a component goes through
during its time in a React application. These phases allow you to run specific
code at key moments in a component’s life, such as when it’s created, updated,
or removed from the screen.
Mounting: Initializes, renders, and mounts the component
(componentDidMount()).
1. Mounting
Mounting refers to the process of creating and inserting a component into the
DOM for the first time in a React application. During mounting, React initializes
the component, sets up its internal state (if any), and inserts it into the DOM.
constructor
getDerivedStateFromProps
render()
componentDidMount()
constructor()
Method to initialize state and bind methods. Executed before the component is
mounted.
constructor(props) {
this.state = {
};
console.log("Constructor called");
getDerivedStateFromProps(props, state)
Used for updating the state based on props. Executed before every render.
render() method
render() {
return (
<div>
</div>
);
componentDidMount() Function
This function is invoked right after the component is mounted on the DOM, i.e.
this function gets invoked once after the render() function is executed for the first
time.
componentDidMount() {
fetch("https://api.example.com/data")
2. Updation
getDerivedStateFromProps
setState() Function
shouldComponentUpdate()
getSnapshotBeforeUpdate() Method
componentDidUpdate()
getDerivedStateFromProps
getDerivedStateFromProps(props, state) is a static method that is called just before
the render() method in both the mounting and updating phase in React. It takes
updated props and the current state as arguments.
setState()
This is not particularly a Lifecycle function and can be invoked explicitly at any
instant. This function is used to update the state of a component.
}));
shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState)
getSnapshotBeforeUpdate() Method
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate()
Similarly, this function is invoked after the component is rendered, i.e., this
function gets invoked once after the render() function is executed after the
updation of State or Props.
3. Unmounting
This is the final phase of the lifecycle of the component, which is the phase of
unmounting the component from the DOM. The following function is the sole
member of this phase.
componentWillUnmount()
This function is invoked before the component is finally unmounted from the
DOM, i.e., this function gets invoked once before the component is removed from
the page, and this denotes the end of the lifecycle.
Program
// Filename - src/index.js:
constructor(props) {
super(props);
}
componentDidMount() {
console.log("componentDidMount()");
changeState() {
render() {
return (
<div>
<h1>
React.js, Hello
{this.state.hello}
</h1>
<h2>
<a
onClick={this.changeState.bind(
this
)}
>
Press Here!
</a>
</h2>
</div>
);
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate()");
return true;
componentDidUpdate() {
console.log("componentDidUpdate()");
document.getElementById("root")
);
root.render(<Test />);
3. useState, useEffect, useHistory and useRef – React Hooks with example
programs.
useState Hooks are used to add the state variables in the components. For using the
useState hook we have to import it in the component.
Syntax
function handleClick() {
setCount(count + 1);
return (
<button onClick={handleClick}>
Click {count} me
</button>
);
In this example
useState(0): Initializes count with 0.
setCount(count + 1): Updates the state by adding 1 to the current value.
setCount(count – 1): Decreases the state by 1.
Managing Form Input State
useState is also useful for handling form input fields dynamically.
import React, { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const [age, setAge] = useState('');
const [submitted, setSubmitted] = useState(false);
const handleSubmit = () => {
setSubmitted(true);
};
return (
<div>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter your name"
/>
<input
type="number"
value={age}
onChange={(e) => setAge(e.target.value)}
placeholder="Enter your age"
/>
<button onClick={handleSubmit}>Submit</button>
{submitted && <p>Form Submitted!</p>}
</div>
);
}
In this example
React useEffect hook handles the effects of the dependency array. The useEffect
Hook allows us to perform side effects on the components. fetching data, directly
updating the DOM and timers are some side effects. It is called every time any
state if the dependency array is modified or updated.
//HookCounterOne.js
useEffect(() => {
}, [count]);
return (
<div>
</button>
</div>
);
Ref Hooks
Ref Hooks like useRef provide access to DOM nodes or persist values without
causing re-renders.
function Focus() {
return (
<div>
<button onClick={focus}>Focus</button>
</div>
);
useRef stores a reference to the input element, allowing the focus function to
programmatically set focus on it.
UseHistory
The useHistory hook is a React Router hook that allows you to access the history
object. The history object contains information about the current URL, as well as
the previous and next URLs in the history stack.
Example
// App.js
function App() {
history.push('/dashboard');
};
setIsLoggedIn(false);
history.push('/login');
};
history.goBack();
};
return (
<div>
{isLoggedIn ? (
<button onClick={handleLogout}>Logout</button>
):(
<button onClick={handleLogin}>Login</button>
)}
<button onClick={goBack}
Go Back
</button>
</div>
);
In React, props are used to pass data from a parent to a child component,
while PropTypes (from the prop-types library) helps validate the types of those
props to catch errors early, ensuring data integrity.
Data Flow: Props enable unidirectional data flow; from parent to child.
// Parent Component (App.js)
function App() {
return (
);
function Greeting(props) {
return (
);
Concept: PropTypes allows you to define the expected types of props a component
receives and helps catch type errors during development.
Benefits:
Improved Code Readability: Developers understand the expected data types for
props at a glance.
Early Error Detection: React warnings will alert developers in the browser console
when incorrect types are passed.
Reduced Bugs: PropTypes prevent runtime errors caused by unexpected data types.
// Import PropTypes
return (
);
Greeting.propTypes = {
};
Object Type.
function Person(props) {
return (
<div>
</div>
);
Person.propTypes = {
person: PropTypes.object,
};
Array Type.
function DisplayList(props){
return(
<div>
<ul>
{props.items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
</div>
);
DisplayList.propTypes = {
items: PropTypes.arrayOf(PropTypes.string)
function ImageDisplay(props) {
return(
<div>
<h1>{props.title}</h1>
<img src={props.image} alt={props.title}/>
</div>
);
ImageDisplay.propTypes = {
title: PropTypes.node,
image: PropTypes.string.isRequired,
Uncontrolled Components
Uncontrolled Components are the components that do not rely on the React state
and are handled by the DOM (Document Object Model). So in order to access any
value that has been entered we take the help of refs.
// FileName - App.js
import "./App.css";
function App() {
function handleSubmit() {
alert(`Name: ${inputRef.current.value}`);
return (
<div className="App">
<h3>Uncontrolled Component</h3>
<form onSubmit={handleSubmit}>
<label>Name :</label>
<input
type="text"
name="name"
ref={inputRef}
/>
<button type="submit">Submit</button>
</form>
</div>
);
Output
Controlled Components
In React, Controlled Components are those in which form’s data is handled by the
component’s state. It takes its current value through props and makes changes
through callbacks like onClick, onChange, etc. A parent component manages its
own state and passes the new values as props to the controlled component.
// FileName - App.js
import { useState } from "react";
import "./App.css";
function App() {
const [name, setName] = useState("");
function handleSubmit() {
alert(`Name: ${name}`);
}
return (
<div className="App">
<h3>Controlled Component</h3>
<form onSubmit={handleSubmit}>
<label>Name:</label>
<input
name="name"
value={name}
onChange={(e) =>
setName(e.target.value)
}
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
return (
<div>
</div>
);
};
};
// Base component
};
Render Props
Render Props is another pattern where a component takes a function as a prop, and
that function is used to render the UI. This can be an auxiliary way of injecting
dynamic behavior into a component.
setMousePosition({
x: event.clientX,
y: event.clientY,
});
};
return (
{render(mousePosition)}
</div>
);
};
<MouseTracker
render={(mousePosition) => (
)}
/>
);
You can create auxiliary components for managing shared state across an
application using React’s Context API. A context provider component can provide
values to other components that need it.
Example:
// Create context
return (
{children}
</ThemeContext.Provider>
);
};
return (
<div>
</div>
);
};
<ThemeProvider>
<ThemedComponent />
</ThemeProvider>
);
Conditional Rendering
return (
<div>
</button>
</div>
);
};
Example2
if (!isLoggedIn) {
return (
<div>
</div>
);
return (
<div>
<p>Welcome, User!</p>
);
};
return (
<div>
<h3>List of Fruits</h3>
<ul>
<li key={index}>{fruit}</li>
))}
</ul>
</div>
);
};
BrowserRouter: This is a wrapper component that uses the HTML5 history API to
keep the UI in sync with the URL.
Route: This component is used to define which component should render based on
the current URL.
Link: This component is used to navigate between different routes, similar to <a>
tags in traditional HTML.
Switch: This component is used to render the first matching <Route> among its
children.
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Switch>
</Switch>
</Router>
);
};
Unit 4:
1. Event Bubbling in React
Event bubbling refers to the way events propagate in the DOM. In React, events
also bubble up from the target element to the root of the component tree. This
means that an event triggered by an element can be caught by its parent or even its
ancestor elements, unless it's stopped.
alert('Parent clicked!');
};
alert('Child clicked!');
};
return (
<div onClick={handleClickParent}>
<h1>Parent</h1>
<div onClick={handleClickChild}>
<h2>Child</h2>
</div>
</div>
);
};
Explanation:
When you click on the Child div, the handleClickChild event handler is triggered.
If e.stopPropagation() is used, the event doesn't bubble to the parent.
CSS Modules are a way to scope CSS to a specific component to avoid global style
conflicts. Each class name is scoped locally by default.
/* styles.module.css */
.container {
background-color: lightblue;
padding: 20px;
.heading {
color: green;
// MyComponent.jsx
import React from 'react';
return (
<div className={styles.container}>
</div>
);
};
Explanation:
The styles object contains the scoped class names like styles.container and
styles.heading, which are automatically generated by CSS Modules.
This ensures that the styles are scoped to MyComponent only, preventing them
from affecting other components.
In React, data binding is typically done through state and props. The most common
form of data binding is one-way binding, where the state of the component is
passed down to the child components via props.
return (
<div>
<h1>Hello, {name}</h1>
<input
type="text"
/>
</div>
);
};
Explanation:
When the input changes, the state is updated using setName, which triggers a
re-render.
The h1 tag dynamically displays the name that the user enters.
4. Wrapper Components
Wrapper components are React components that are used to wrap other
components to modify their behavior or appearance, often for reusability or adding
common functionality (e.g., adding styling or passing down props).
};
return (
<Wrapper>
<h1>Wrapped Component</h1>
</Wrapper>
);
};
Explanation:
The Wrapper component is a simple wrapper that adds a border and padding
around its children.
In the MyComponent, any content inside <Wrapper> will be rendered within the
div of the Wrapper component.
React uses synthetic events (a cross-browser wrapper around the browser's native
events).
React event handlers are written in camelCase (e.g., onClick instead of onclick).
The event handler functions are passed as references, not strings.
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
};
Explanation:
handleClick is the event handler that is triggered when the button is clicked.
The event handler updates the state (setCount), which causes the component to
re-render and display the updated count.
In some cases, you might want to prevent the default behavior of an event, such as
submitting a form when the "Enter" key is pressed.
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={input}
placeholder="Type something"
/>
<button type="submit">Submit</button>
</form>
);
};
The e.preventDefault() inside the handleSubmit function prevents the form from
submitting in the default way (which would reload the page).
Summary:
Event Bubbling: React events bubble up from the target element to the parent
elements. You can stop bubbling using e.stopPropagation().
Data Binding: In React, data binding is typically one-way, passing data from state
or props to child components.
Event Handling: React event handlers are passed as functions, and you can prevent
default behavior or stop event propagation.
Unit 3
In short:
HOC can be used as a container for another component (in this case it's often
called auxiliary component or Aux in the project). In this case it simply
takes props as argument and returns children:
return (
<Aux>
<td>Column 1</td>
<td>Column 2</td>
</Aux>
);
React.Fragment
return (
<React.Fragment>
<td>Column 1</td>
<td>Column 2</td>
</React.Fragment>
);
OR fragments can also be declared with a short syntax which looks like an
empty tag:
return (
<>
<td>Column 1</td>
<td>Column 2</td>
</>
);
Conclusion:
• It's possible to use both variants since they do the same job - allow to
return multiple JSX elements without adding extra layer
• Using React.Fragment has more benefits though, since you don't need to
create extra component and it’s a tiny bit faster and has less memory
usage (no need to create an extra DOM node).