[go: up one dir, main page]

0% found this document useful (0 votes)
4 views44 pages

WDF Unit 3 and 4 PDF

The document provides an overview of React components, including class and functional components, and their lifecycle methods. It explains the use of React Hooks such as useState, useEffect, useHistory, and useRef, along with examples for managing state and side effects. Additionally, it covers the use of props and PropTypes for data passing and type validation in React applications.

Uploaded by

oopsitsmysteria
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)
4 views44 pages

WDF Unit 3 and 4 PDF

The document provides an overview of React components, including class and functional components, and their lifecycle methods. It explains the use of React Hooks such as useState, useEffect, useHistory, and useRef, along with examples for managing state and side effects. Additionally, it covers the use of props and PropTypes for data passing and type validation in React applications.

Uploaded by

oopsitsmysteria
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/ 44

Unit 3:

1. Class components and functional component

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.

There are two main types of components in React:

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

import React from 'react';

// Function component using function keyword

function FunctionComponent(props) {

return (

<div>

<h1>Hello, {props.name}!</h1>

<p>This is a function component.</p>

</div>

);

// Function component using arrow function syntax

const FunctionComponent = (props) => {

return (
<div>

<h1>Hello, {props.name}!</h1>

<p>This is a function component.</p>

</div>

);

};

export default FunctionComponent;

(useState), function components can now manage state using Hooks.

import React, { useState } from 'react';

const FunctionComponent = () => {

// Using useState Hook to manage state

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

return (

<div>

<p>Count: {count}</p>

<button onClick={() => setCount(count + 1)}>Increment</button>

</div>

);

};

export default FunctionComponent;

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

import React, { Component } from 'react';

// Define a class component that extends React.Component or


React.PureComponent

class ClassComponent extends Component {

// Define constructor if necessary

constructor(props) {

super(props);

// Initialize state if needed

this.state = {

count: 0

};

// Define lifecycle methods if necessary

componentDidMount() {

// Code to run after the component is mounted

// Define instance methods if necessary

handleClick = () => {

// Update state or perform other logic

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

// Define render() method to return JSX


render() {

return (

<div>

<p>Count: {this.state.count}</p>

<button onClick={this.handleClick}>Increment</button>

</div>

);

export default ClassComponent;

2. React component lifecycle methods with example programs.

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()).

Updating: Handles state/prop changes, re-renders, and updates


(componentDidUpdate()).

Unmounting: Cleans up before removal (componentWillUnmount()).

Phases of Lifecycle in React Components

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) {

super(props); // Always call super(props) before using this.props

this.state = {

count: 0, // Initial state

};

console.log("Constructor called");

getDerivedStateFromProps(props, state)

Used for updating the state based on props. Executed before every render.

static getDerivedStateFromProps(props, state) {

if (props.value !== state.value) {

return { value: props.value }; // Update state based on new props

return null; // No changes to state

render() method

Responsible for rendering JSX and updating the DOM.

render() {

return (

<div>

<h1>Hello, React Lifecycle!</h1>

</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() {

console.log("Component has been mounted");

// Example: Fetch data from an API

fetch("https://api.example.com/data")

.then(response => response.json())

.then(data => this.setState({ data }));

2. Updation

Updating refers to the process of a component being re-rendered due to changes in


its state or props. This phase occurs whenever a component’s internal state is
modified or its parent component passes new props. When an update happens,
React re-renders the component to reflect the changes and ensures that the DOM is
updated accordingly.

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.

static getDerivedStateFromProps(props, state) {

if (props.name !== state.name) {

return { name: props.name }; // Update state with new props

return null; // No state change

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.

this.setState((prevState, props) => ({

counter: prevState.count + props.diff

}));

shouldComponentUpdate()

shouldComponentUpdate() Is a lifecycle method in React class components that


determines whether a component should re-render. It compares the current and
next props/states and returns true if the component should update or false if it
should not.

shouldComponentUpdate(nextProps, nextState)

It returns true or false, if false, then render(), componentWillUpdate(), and


componentDidUpdate() method does not get invoked.

getSnapshotBeforeUpdate() Method

The getSnapshotBeforeUpdate() method is invoked just before the DOM is being


rendered. It is used to store the previous values of the state after the DOM is
updated.

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.

componentDidUpdate(prevProps, prevState, snapshot)

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:

import React from "react";

import ReactDOM from 'react-dom';

class Test extends React.Component {

constructor(props) {

super(props);

this.state = { hello: "World!" };

}
componentDidMount() {

console.log("componentDidMount()");

changeState() {

this.setState({ hello: "React!" });

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()");

const root = ReactDOM.createRoot(

document.getElementById("root")

);

root.render(<Test />);
3. useState, useEffect, useHistory and useRef – React Hooks with example
programs.

React useState Hook

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

const [state, setState] = useState(initialState)

state: It is the value of the current state.

setState: It is the function that is used to update the state.

initialState: It is the initial value of the state.


Example

import { useState } from 'react';

export default function Counter() {

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

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>
);
}

export default Form;

In this example

useState(”): Initializes name and age with an empty string.

onChange={(e): setName(e.target.value)}: Updates name state as the user types.

onChange={(e): setAge(e.target.value)}: Updates age state as the user types.

setSubmitted(true): Marks the form as submitted.

ReactJS useEffect Hook

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 is defined here

import { useState, useEffect } from "react";


function HookCounterOne() {

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

useEffect(() => {

document.title = `You clicked ${count} times`;

}, [count]);

return (

<div>

<button onClick={() => setCount((prevCount) => prevCount + 1)}>

Click {count} times{" "}

</button>

</div>

);

export default HookCounterOne;

Ref Hooks

Ref Hooks like useRef provide access to DOM nodes or persist values without
causing re-renders.

import React, { useRef } from "react";

function Focus() {

const input = useRef();


const focus = () => input.current.focus();

return (

<div>

<input ref={input} type="text" />

<button onClick={focus}>Focus</button>

</div>

);

export default Focus;

useRef stores a reference to the input element, allowing the focus function to
programmatically set focus on it.

Updating inputRef does not cause the component to re-render.

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

import React, { useState } from 'react';

import { useHistory } from 'react-router-dom';

function App() {

const [isLoggedIn, setIsLoggedIn] = useState(false);

const history = useHistory();

const handleLogin = () => {


setIsLoggedIn(true);

// Navigate to the dashboard page programmatically

history.push('/dashboard');

};

const handleLogout = () => {

setIsLoggedIn(false);

// Navigate to the login page programmatically

history.push('/login');

};

const goBack = () => {

// Navigate back one step in history

history.goBack();

};

return (

<div>

{isLoggedIn ? (

<button onClick={handleLogout}>Logout</button>

):(

<button onClick={handleLogin}>Login</button>

)}

<button onClick={goBack}

disabled={history.length <= 1}>

Go Back
</button>

</div>

);

export default App;

4. props and PropTypes in React with Programs.

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.

Here's a breakdown with examples:

1. Props: Passing Data

Concept: Props are essentially properties passed to a React component, similar to


attributes in HTML tags. They allow you to customize the behavior and data of a
child component from its parent.

Data Flow: Props enable unidirectional data flow; from parent to child.
// Parent Component (App.js)

function App() {

return (

<Greeting name="John" age={30} />

);

// Child Component (Greeting.js)

function Greeting(props) {

return (

<h1>Hello, {props.name}! You are {props.age} years old.</h1>

);

PropTypes: Type Checking

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

import PropTypes from 'prop-types';

//Child Component (Greeting.js)


function Greeting(props) {

return (

<h1>Hello, {props.name}! You are {props.age} years old.</h1>

);

//Define the PropTypes for Greeting component

Greeting.propTypes = {

name: PropTypes.string.isRequired, // Requires name to be a string

age: PropTypes.number // Optionally, age can be a number

};

Using PropTypes with more types

Object Type.

function Person(props) {

const { name, age, occupation } = props.person;

return (

<div>

Name: {name}, Age: {age}, Occupation: {occupation}

</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)

React Node type.

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,

5. Controlled and UnControlled Components.

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 React, { useRef } from "react";

import "./App.css";

function App() {

const inputRef = useRef(null);

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>

);

export default App;

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>
);
}

export default App;

6. Higher-Order Components (HOCs)

A Higher-Order Component (HOC) is a pattern used to add functionality to a


component. You can think of an HOC as an auxiliary component that wraps
another component and injects additional logic or functionality (like data fetching
or authentication checks).

import React from 'react';

// Higher-order component that adds additional functionality

const withTitle = (WrappedComponent) => {


return (props) => {

return (

<div>

<h1>My Custom Title</h1>

<WrappedComponent {...props} />

</div>

);

};

};

// Base component

const MyComponent = () => {

return <p>This is my component!</p>;

};

// Wrapping the component with the HOC

const MyComponentWithTitle = withTitle(MyComponent);

export default MyComponentWithTitle;

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.

import React, { useState } from 'react';

const MouseTracker = ({ render }) => {


const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });

const handleMouseMove = (event) => {

setMousePosition({

x: event.clientX,

y: event.clientY,

});

};

return (

<div onMouseMove={handleMouseMove} style={{ height: '100vh' }}>

{render(mousePosition)}

</div>

);

};

const MyComponent = () => (

<MouseTracker

render={(mousePosition) => (

<p>The mouse position is {mousePosition.x}, {mousePosition.y}</p>

)}

/>

);

export default MyComponent;


As the cursor moves around the screen, the component displays its (x, y)
coordinates in a <p>.

Context Provider Components

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:

import React, { createContext, useContext, useState } from 'react';

// Create context

const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {

const [theme, setTheme] = useState('light');

const toggleTheme = () => setTheme((prev) => (prev === 'light' ? 'dark' :


'light'));

return (

<ThemeContext.Provider value={{ theme, toggleTheme }}>

{children}

</ThemeContext.Provider>

);

};

const ThemedComponent = () => {

const { theme, toggleTheme } = useContext(ThemeContext);

return (
<div>

<p>The current theme is {theme}</p>

<button onClick={toggleTheme}>Toggle Theme</button>

</div>

);

};

const App = () => (

<ThemeProvider>

<ThemedComponent />

</ThemeProvider>

);

export default App;

7. Conditional rendering and iterative rendering.

Conditional Rendering

Conditional rendering in React is the process of rendering different UI elements or


components depending on a condition or state.

import React, { useState } from 'react';

const MyComponent = () => {

const [isLoggedIn, setIsLoggedIn] = useState(false);

return (

<div>

{isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in.</p>}


<button onClick={() => setIsLoggedIn(!isLoggedIn)}>

Toggle Login Status

</button>

</div>

);

};

export default MyComponent;

Example2

import React, { useState } from 'react';

const MyComponent = () => {

const [isLoggedIn, setIsLoggedIn] = useState(false);

if (!isLoggedIn) {

return (

<div>

<p>Please log in.</p>

<button onClick={() => setIsLoggedIn(true)}>Log In</button>

</div>

);

return (

<div>

<p>Welcome, User!</p>

<button onClick={() => setIsLoggedIn(false)}>Log Out</button>


</div>

);

};

export default MyComponent;

Iterative Rendering (Rendering Lists)

Iterative rendering refers to rendering a list of elements or components based on an


array of data. React provides the .map() method to iterate over arrays and render a
component for each item in the array.

import React from 'react';

const MyComponent = () => {

const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

return (

<div>

<h3>List of Fruits</h3>

<ul>

{fruits.map((fruit, index) => (

<li key={index}>{fruit}</li>

))}

</ul>

</div>

);

};

export default MyComponent;


8. React routers.

React Router is a powerful library used to handle routing in a React application. It


allows you to navigate between different views or components, manage dynamic
URLs, and control the browser history. It enables single-page applications (SPA),
where the entire page does not reload when navigating between pages. Instead,
React Router updates the view based on the URL.

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.

useHistory, useLocation, useParams, useRouteMatch: These are hooks provided by


React Router for accessing and manipulating routing information.

import React from 'react';

import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

const Home = () => <h2>Home Page</h2>;

const About = () => <h2>About Page</h2>;

const Contact = () => <h2>Contact Page</h2>;

const App = () => {

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>

<Route exact path="/" component={Home} />

<Route path="/about" component={About} />

<Route path="/contact" component={Contact} />

</Switch>

</Router>

);

};

export default App;

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.

Example of Event Bubbling:

import React from 'react';

const ParentComponent = () => {

const handleClickParent = () => {

alert('Parent clicked!');

};

const handleClickChild = (e) => {

alert('Child clicked!');

e.stopPropagation(); // This prevents the event from bubbling to the


parent

};

return (

<div onClick={handleClickParent}>

<h1>Parent</h1>

<div onClick={handleClickChild}>

<h2>Child</h2>

</div>

</div>

);
};

export default ParentComponent;

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.

Without e.stopPropagation(), clicking on the Child would also trigger the


handleClickParent handler because of event bubbling.

2. CSS Module Integration in React

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.

Steps for Using CSS Modules:

Create a CSS file with a .module.css extension.

Import and use the CSS classes in the React component.

Example of CSS Module:

/* styles.module.css */

.container {

background-color: lightblue;

padding: 20px;

.heading {

color: green;

// MyComponent.jsx
import React from 'react';

import styles from './styles.module.css';

const MyComponent = () => {

return (

<div className={styles.container}>

<h1 className={styles.heading}>Hello, CSS Modules!</h1>

</div>

);

};

export default MyComponent;

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.

3. Data Binding in React

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.

Example of Data Binding (One-way binding with state and props):

import React, { useState } from 'react';

const MyComponent = () => {

const [name, setName] = useState('John');

return (
<div>

<h1>Hello, {name}</h1>

<input

type="text"

value={name} // Binding the input value to the state

onChange={(e) => setName(e.target.value)} // Updating the state when the


input changes

/>

</div>

);

};

export default MyComponent;

Explanation:

The value of the input field is bound to the state name.

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).

Example of a Wrapper Component:

import React from 'react';

const Wrapper = ({ children }) => {


return <div style={{ border: '2px solid black', padding: '10px'
}}>{children}</div>;

};

const MyComponent = () => {

return (

<Wrapper>

<h1>Wrapped Component</h1>

<p>This is inside the wrapper!</p>

</Wrapper>

);

};

export default MyComponent;

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.

5. Event Handling in React

Event handling in React is similar to the way it is done in traditional JavaScript,


but with a few differences:

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.

Example of Event Handling in React:

import React, { useState } from 'react';

const EventHandlingComponent = () => {

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

const handleClick = () => {

setCount(count + 1);

};

return (

<div>

<p>Count: {count}</p>

<button onClick={handleClick}>Increment</button>

</div>

);

};

export default EventHandlingComponent;

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.

Example of Preventing Default Event Behavior:

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.

import React, { useState } from 'react';

const FormComponent = () => {

const [input, setInput] = useState('');

const handleSubmit = (e) => {

e.preventDefault(); // Prevents the form from submitting

alert('Form submitted with input: ' + input);

};

return (

<form onSubmit={handleSubmit}>

<input

type="text"

value={input}

onChange={(e) => setInput(e.target.value)}

placeholder="Type something"

/>

<button type="submit">Submit</button>

</form>

);

};

export default FormComponent;


Explanation:

The e.preventDefault() inside the handleSubmit function prevents the form from
submitting in the default way (which would reload the page).

Instead, it shows an alert with the input value.

Summary:

Event Bubbling: React events bubble up from the target element to the parent
elements. You can stop bubbling using e.stopPropagation().

CSS Module Integration: Use .module.css files to scope styles to a particular


component, ensuring no conflicts.

Data Binding: In React, data binding is typically one-way, passing data from state
or props to child components.

Wrapper Components: Wrapper components are used to add functionality or styles


to other components.

Event Handling: React event handlers are passed as functions, and you can prevent
default behavior or stop event propagation.

Unit 3

Auxiliary component in React

Aux (Auxiliary) Components or HOC

A higher-order component (HOC) in React is a pattern used to share common


functionality between components without repeating code. HOC is actually
not a component though, it is a function. A HOC function takes a component
as an argument and returns a component. It transforms a component into
another component and adds additional data or functionality.

In short:

const NewComponent = (BaseComponent) => {

// ... create new component from old one and update


return UpdatedComponent

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:

const Aux = (props) => props.children;

export default Aux;

In our example we can simply change wrapper div with Aux:

const Columns = () => {

return (

<Aux>

<td>Column 1</td>

<td>Column 2</td>

</Aux>

);

React.Fragment

React.Fragment was introduced in React 16.2.0.


React.Fragment let you group a list of children without adding extra nodes to
the DOM because fragments are not rendered to the DOM. So basically we
use React.Fragment where we would normally use a wrapper div.

In our example we can simply change wrapper div with React.Fragment:

const Columns = () => {

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:

const Columns = () => {

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).

You might also like