Sunday, 5 January 2025

How to Develop a custom hook in React?

A custom hook in React is a function that starts with 'use' and allows you to encapsulate logic that can be reused across multiple components. Custom hooks use existing React hooks (like useState, useEffect, etc.) internally and help in abstracting out reusable pieces of logic from components.


Why Use Custom Hooks?

·      Reusability: Instead of duplicating logic across components, you can move that logic into a custom hook and share it.

·      Separation of Concerns: Custom hooks help in keeping your component clean by moving logic (like fetching data, managing local storage, etc.) into separate, reusable functions.

 

 

Let’s build an application to understand custom hook better.

 

Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘custom-hook’

 

Project structure looks like below.

 


Step 2: Create hooks folder in src and define useLogger hook.

 

useLogger.js

import { useEffect } from "react";

export default function useLogger(componentName) {
  useEffect(() => {
    console.log(`${componentName} mounted`);

    // Cleanup called when the component is unmounted
    return () => {
      console.log(`${componentName} unmounted`);
    };
  }, []); // Empty dependency array means this runs only on mount and unmount

  useEffect(() => {
    console.log(`${componentName} updated`);
  });
}

Step 3: Create components folder in src and define Counter component.

 

Counter.jsx

import { useState } from "react";
import useLogger from "../hooks/useLogger";

export default function Counter() {
  const [count, setCount] = useState(0);
  useLogger("Counter");

  return (
    <>
      <p>Counter : {count}</p>

      <button onClick={() => setCount((currentCount) => count + 1)}>
        Click Me
      </button>
    </>
  );
}

Update App.jsx file with below content.

 

App.jsx

import React, { useState } from 'react';
import Counter from './components/Counter';

const App = () => {
  const [isVisible, setIsVisible] = useState(true);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? 'Hide Counter' : 'Show Counter'}
      </button>
      
      {isVisible && <Counter />}
    </div>
  );
};

export default App;

Update main.jsx with below content.

 

main.jsx

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

createRoot(document.getElementById("root")).render(<App />);

Step 4: Build and run the application by executing below commands.

  cd custom-hook
  npm install
  npm run dev


 

Experiment with the buttons ‘Hide Counter’ and ‘Click Me’, you can see following kind of messages in console.


 

You can download this application from this link.


Previous                                                    Next                                                    Home

Comparison Operators in JavaScript

 

Comparison operators in JavaScript are used to compare two values and return a boolean result (true or false). They are essential for making decisions in your code.

 

1. Equality (==)

The equality operator checks if two values are equal, performing type coercion if necessary.

 

Syntax

value1 == value2;

 

Example

console.log(5 == '5'); // Output: true

 

In this example, 5 (number) is compared to '5' (string). Due to type coercion, they are considered equal.

 

2. Strict Equality (===)

The strict equality operator checks if two values are equal and of the same type, without performing type coercion.

 

Syntax

value1 === value2;

 

Example

console.log(5 === '5'); // Output: false

 

Here, 5 (number) is not strictly equal to '5' (string) because their types are different.

 

3. Inequality (!=)

The inequality operator checks if two values are not equal, performing type coercion if necessary.

 

Syntax

value1 != value2;

 

Example

console.log(5 != '5'); // Output: false

 

In this case, 5 and '5' are considered equal due to type coercion, so the result is false.

 

4. Strict Inequality (!==)

The strict inequality operator checks if two values are not equal or not of the same type, without performing type coercion.

 

Syntax

value1 !== value2;

 

Example

console.log(5 !== '5'); // Output: true

 

Here, 5 (number) is strictly not equal to '5' (string) because their types differ.

 

5. Greater Than (>)

The greater than operator checks if one value is greater than another.

 

Syntax

value1 > value2;

 

Example

console.log(10 > 5); // Output: true

 

In this example, 10 is greater than 5, so the result is true.

 

6. Greater Than or Equal To (>=)

The greater than or equal to operator checks if one value is greater than or equal to another.

 

Syntax

value1 >= value2;

 

Example

console.log(10 >= 10); // Output: true

 

Here, 10 is equal to 10, so the result is true.

 

7. Less Than (<)

The less than operator checks if one value is less than another.

 

Syntax

value1 < value2;

 

Example

console.log(5 < 10); // Output: true

 

In this case, 5 is less than 10, so the result is true.

 

8. Less Than or Equal To (<=)

The less than or equal to operator checks if one value is less than or equal to another.

 

Syntax

value1 <= value2;

 

Example

console.log(5 <= 5); // Output: true

 

Here, 5 is equal to 5, so the result is true.

 

These operators are fundamental for making comparisons and decisions in JavaScript.

 

Find the below application.

 

comparisonOperators.js 

console.log(`5 == '5' : ${5 == '5'}`);
console.log(`5 == 5 : ${5 == 5}`);
console.log(`5 === '5' : ${5 === '5'}`);
console.log(`5 != '5' : ${5 != '5'}`);
console.log(`5 != 5 : ${5 != 5}`);
console.log(`5 !== '5' : ${5 !== '5'}`);
console.log(`10 > 5 : ${10 > 5}`);
console.log(`10 >= 10 : ${10 >= 10}`);
console.log(`5 < 10 : ${5 < 10}`);
console.log(`5 <= 5 : ${5 <= 5}`);

 

Output

5 == '5' : true
5 == 5 : true
5 === '5' : false
5 != '5' : false
5 != 5 : false
5 !== '5' : true
10 > 5 : true
10 >= 10 : true
5 < 10 : true
5 <= 5 : true

 

Previous                                                    Next                                                    Home

Understanding Height and Width in the CSS Box Model

This is continuation to my previous post.

The CSS box model is a foundational concept for web layout and design. It consists of margins, borders, padding, and the content area. The height and width properties control the size of the content area of an element. Let's explore these properties in detail.

 


The CSS box model consists of,

1.   Content: The actual content of the box (text, images, etc.).

2.   Padding: Space between the content and the border.

3.   Border: A border surrounding the padding (if any) and content.

4.   Margin: Space outside the border, separating the element from others.

 

When setting height and width, you're defining the size of the content area.

 

Different values for height and weight properties

1. Absolute Values

1.1 Pixels (px)

Fixed units, independent of other elements or viewport.

 

Example

width: 300px;

 

1.2 Points (pt), Centimeters (cm), Inches (in)

Rarely used for web, more common in print media.

 

Example

height: 5cm;

 

2. Relative Values

2.1 Percentage (%)

Relative to the parent element's dimensions.

Example: width: 50%; makes the width half of the parent's width.

 

2.2 Em and Rem (em, rem)

Relative to font size (1 em = current font size, 1 rem = root font size). Useful for scalable layouts.

Example: width: 10em;

 

2.3 View Width (vw) and View Height (vh)

Relative to the viewport size (1 vw = 1% of viewport width, 1 vh = 1% of viewport height). Useful for making elements responsive to viewport size changes.

 

Example: width: 50vw; makes the width half of the viewport's width.

 

2.4 Minimum and Maximum Values

min-width, max-width, min-height, max-height: Constraints to prevent elements from becoming too small or too large.

Example: min-width: 200px; max-width: 100%;

 

Special value for height and width properties

1. Auto

The browser calculates the size automatically.

Example: width: auto;

 

2. Initial

Sets the property to its default value.

Example: width: initial;

 

3. Inherit

Inherits the value from the parent element.

Example: width: inherit;

 

Best Practices for Setting Height and Width

1.   Use Relative Units for Responsive Design. Utilize %, vw, vh, em, and rem to create layouts that adjust to different screen sizes.

Example: width: 50%;

2.   Avoid Fixed Pixels for Main Layouts. Fixed pixel values can cause issues on devices with different screen sizes or resolutions. Instead, use percentages or viewport units.

 

3.   Set Min and Max Constraints. Prevents elements from shrinking too much or expanding beyond reasonable limits.

Example: min-width: 200px; max-width: 1200px;

 

height-width.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Box Model and Units Example</title>
    <style>
        /* Basic styles for body */
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
        }

        /* Header with full viewport height */
        .header {
            background-color: #4CAF50;
            height: 100vh; /* Full viewport height */
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 5vw; /* Responsive font size based on viewport width */
            text-align: center;
        }

        /* Main content area */
        .content {
            width: 80%; /* 80% of the parent's width */
            margin: 20px auto;
            padding: 20px;
            border: 4px solid #ddd;
            background-color: #e9e9e9;
        }

        /* Footer with fixed height */
        .footer {
            background-color: #333;
            color: white;
            height: 60px; /* Fixed height */
            width: 100%; /* Full width of the parent/container */
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* Responsive box example using vw, vh */
        .responsive-box {
            background-color: #2196F3;
            color: white;
            width: 50vw; /* 50% of viewport width */
            height: 30vh; /* 30% of viewport height */
            margin: 20px auto;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* Box with min and max width constraints */
        .constrained-box {
            background-color: #FF9800;
            color: white;
            padding: 20px;
            min-width: 200px; /* Minimum width */
            max-width: 80%; /* Maximum width relative to the parent */
            margin: 20px auto;
            text-align: center;
        }

    </style>
</head>
<body>

    <!-- Header section with full viewport height -->
    <header class="header">
        Full Viewport Header (100vh height)
    </header>

    <!-- Main content area -->
    <div class="content">
        <h2>Main Content Area</h2>
        <p>This content area uses width set in percentage (80% of parent width) with padding and border to demonstrate the CSS box model. The `box-sizing: border-box;` ensures that padding and border are included in the width.</p>
    </div>

    <!-- Responsive box using viewport units -->
    <div class="responsive-box">
        50vw x 30vh Box
    </div>

    <!-- Box with minimum and maximum width constraints -->
    <div class="constrained-box">
        This box has min-width of 200px and max-width of 80%. It prevents the box from being too small or too large.
    </div>

    <!-- Footer section with fixed height -->
    <footer class="footer">
        Fixed Height Footer (60px)
    </footer>

</body>
</html>

Open the above html page in a browser and see the affect by scrolling down the page.

 

Understanding the Viewport

The viewport is the visible area of the user's browser window where the web content is displayed. It excludes browser toolbars, navigation, and other interface elements.

 

·      Viewport Width (vw): 1vw equals 1% of the viewport's width.

·      Viewport Height (vh): 1vh equals 1% of the viewport's height.

 

When to Use Viewport Height (vh) and Width (vw)

Full-screen Sections

To create sections that fill the entire viewport, use height: 100vh;.

Example: background images that need to take up the full screen.

 

Responsive Font Size

Use vw to make font size responsive to viewport width.

Example: font-size: 3vw; adjusts the font size as the viewport width changes.

 

Creating Dynamic Layouts

Use viewport units for elements that need to adjust dynamically based on screen size, such as modals or floating action buttons.

Example: width: 50vw; height: 30vh; for a model that scales with the screen.


   

Previous                                                    Next                                                    Home

How to Add Descriptive Titles to HTML Tables with ?

The <caption> element in HTML provides a title or description for a table. It is always placed directly inside the <table> element, before any <thead>, <tbody>, or <tr> elements. The <caption> is typically used to describe the content or purpose of the table, making it more accessible, especially for screen readers.

Caption is usually displayed at the top of the table by default, but it can be styled with CSS to appear elsewhere. It improves accessibility by helping users understand the context of the table. Even though it is optional , adding a <caption> is recommended when the table contains data that could benefit from a title.

 

add-caption-to-table.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Table with Caption</title>
    <style>
        table {
            width: 50vw;
            border-collapse: collapse;
        }
        table, th, td {
            border: 1px solid black;
        }
        caption {
            font-weight: bold;
            font-size: 1.2em;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

    <h1>HTML Table Example with a Caption</h1>

    <table>
        <caption>Monthly Sales Report</caption>
        <thead>
            <tr>
                <th>Product</th>
                <th>Sales (Units)</th>
                <th>Revenue ($)</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Product A</td>
                <td>600</td>
                <td>2600</td>
            </tr>
            <tr>
                <td>Product B</td>
                <td>400</td>
                <td>1700</td>
            </tr>
            <tr>
                <td>Product C</td>
                <td>300</td>
                <td>800</td>
            </tr>
        </tbody>
    </table>

</body>
</html>


 

<caption>Monthly Sales Report</caption>: The caption "Monthly Sales Report" is displayed above the table, giving context to the data inside the table and it is styled to stand out with a bold font and a slight margin from the table.

  

Previous                                                    Next                                                    Home