Friday, 10 January 2025

Understanding the HTML form Element: Attributes, Examples, and JavaScript Integration

The <form> element in HTML is used to create an interactive form for users to input data and submit it to a server. Forms are essential for tasks like user registration, login, feedback, and more.


Key Attributes of <form> Element

1.   action: This attribute specifies where the form data should be sent when the form is submitted. The value of the action attribute is typically a URL that points to a server-side script (like a PHP, Python, or JavaScript file) that processes the form data.

 

·      Example

action="/submit-form" means the form data will be sent to the /submit-form URL for processing.

 

2.   method: This attribute specifies how the form data will be sent to the server. There are two common methods:

 

·      GET: Sends the form data appended to the URL as a query string. This is suitable for simple form submissions where the data can be seen in the URL.

 

·      POST: Sends the form data in the body of the request, making it more secure and suitable for sending sensitive data (like passwords).

 

·      Example:

method="POST" means the form data will be sent as a part of the HTTP request body, not in the URL.

 

registration.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Form</title>
</head>
<body>
    <h2>Registration Form</h2>
    <form action="/submit-registration" method="POST">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username" required><br><br>
        
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br><br>
        
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" required><br><br>
        
        <button type="submit">Register</button>
    </form>
</body>
</html>

Above snippet generate below screen.


 

The form asks for a username, email, and password. When the user submits the form by clicking the "Register" button, the data will be sent to /submit-registration using the POST method. This ensures that sensitive data, like the password, is not exposed in the URL.


Previous                                                    Next                                                    Home

Monday, 6 January 2025

Strict Equality (===) and Strict Inequality (!==) Operators in JavaScript

The strict equality (===) and strict inequality (!==) operators are used in JavaScript to compare two values. They are known as strict operators because they do not perform type coercion, meaning that both the value and the type must be the same for the comparison to return true or false.

1. Strict Equality (===) Operator

The === operator checks if two values are equal in both value and type.

It returns true if both the value and the type are the same; otherwise, it returns false.

 

Example 1: Comparing Numbers

let a = 5;
let b = 5;
console.log(`a : ${a}, b : ${b}, a === b : ${a === b}`);

 

‘a === b ‘ is evaluated to true, because both values are 5 and both are of type number

 

Example 2: Comparing Different Types

a = 5;
b = "5";
console.log(`a : ${a}, b : "${b}", a === b : ${a === b}`);

 

‘a===b’ is evaluated to false, because 5 is a number and "5" is a string

 

Example 3: Comparing Booleans

let isActive = true;
let isLoggedIn = true;
console.log(`isActive : ${isActive}, isLoggedIn : ${isLoggedIn}, isActive === isLoggedIn : ${isActive === isLoggedIn}`);

 

isActive === isLoggedIn is evaluated to true, because both are true and both are of type boolean.

 

Example 4: Comparing Objects.

let obj1 = { name: "Alice" };
let obj2 = { name: "Alice" };
console.log(`obj1 : ${JSON.stringify(obj1)}, obj2 : ${JSON.stringify(obj2)}, obj1 === obj2 : ${obj1 === obj2}`);

‘obj1 === obj2’ is evaluated to false, because although the objects look the same, they are different instances in memory

 

Find the below working application.

 

strictEqualityOperator.js

let a = 5;
let b = 5;
console.log(`a : ${a}, b : ${b}, a === b : ${a === b}`);

a = 5;
b = "5";
console.log(`a : ${a}, b : "${b}", a === b : ${a === b}`);

let isActive = true;
let isLoggedIn = true;
console.log(`isActive : ${isActive}, isLoggedIn : ${isLoggedIn}, isActive === isLoggedIn : ${isActive === isLoggedIn}`);

let obj1 = { name: "Alice" };
let obj2 = { name: "Alice" };
console.log(`obj1 : ${JSON.stringify(obj1)}, obj2 : ${JSON.stringify(obj2)}, obj1 === obj2 : ${obj1 === obj2}`);

Output

a : 5, b : 5, a === b : true
a : 5, b : "5", a === b : false
isActive : true, isLoggedIn : true, isActive === isLoggedIn : true
obj1 : {"name":"Alice"}, obj2 : {"name":"Alice"}, obj1 === obj2 : false

Strict Inequality Operator (!==)

The !== operator checks if two values are not equal in either value or type. It returns true if either the value or the type is different; otherwise, it returns false.

 

strictInequalityOperator.js

let a = 5;
let b = 5;
console.log(`a : ${a}, b : ${b}, a !== b : ${a !== b}`);

a = 5;
b = "5";
console.log(`a : ${a}, b : "${b}", a !== b : ${a !== b}`);

let isActive = true;
let isLoggedIn = true;
console.log(`isActive : ${isActive}, isLoggedIn : ${isLoggedIn}, isActive !== isLoggedIn : ${isActive !== isLoggedIn}`);

let obj1 = { name: "Alice" };
let obj2 = { name: "Alice" };
console.log(`obj1 : ${JSON.stringify(obj1)}, obj2 : ${JSON.stringify(obj2)}, obj1 !== obj2 : ${obj1 !== obj2}`);

Output

a : 5, b : 5, a !== b : false
a : 5, b : "5", a !== b : true
isActive : true, isLoggedIn : true, isActive !== isLoggedIn : false
obj1 : {"name":"Alice"}, obj2 : {"name":"Alice"}, obj1 !== obj2 : true



 

Previous                                                    Next                                                    Home

Building a Custom useFetch Hook in React for Effecient Data Fetching

Fetching data from APIs is a common need in React applications, but handling it within components can often become repetitive and cluttered. Using a custom hook like useFetch can simplify the data retrieval, especially for reusable components or cases with complex error and loading states.

In this post, I will walk you through creating a useFetch hook that can handle asynchronous requests, track loading status, and manage errors—all in a reusable, efficient way.

 

What are custom hooks?
Custom hooks in React are functions that start with "use" (like useFetch). They allow you to reuse logic that you’d otherwise have to repeat in different components. So instead of writing the same data-fetching code every time you need it, you can just use the useFetch hook whenever you want to get data from an API.

 

Benefits of using useFetch

·       Code Reuse: You write your data-fetching code once, and you can use it in multiple components.

·       Cleaner Components: With useFetch, your components only have to focus on displaying data. The data-fetching logic is handled in the hook, making components easier to read and maintain.

 

By creating a custom hook, you’re keeping your code neat and saving time.

 

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

 

Project structure looks like below.

 


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

 

useFetch.jsx

import { useEffect, useState } from "react";

export default function useFetch(url) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [data, setData] = useState(null);

  async function fetchData() {
    try {
      setLoading(true);
      console.log(`Fetching Data from the url ${url}`);

      const response = await fetch(url);

      if (!response.ok) {
        setError("Response Is Not OK....");
        return;
      }

      const data = await response.json();
      console.log(data);
      setData(data);
    } catch (error) {
      console.error(error);
      setError(error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    console.log("Triggering the url " + url);
    fetchData();
  }, [url]);

  return { loading, error, data };
}

This useFetch hook is designed to fetch data from a given url using the fetch API. It provides a clean and reusable way to manage loading state, error handling, and the fetched data in React components.

 

State Management

The hook manages three pieces of state using React’s useState:

1.   loading: Tracks whether the data is still being fetched (true/false).

2.   error: Stores any error message that might occur during the fetch process.

3.   data: Holds the fetched data once the request is successful.

 

These states are initialized as follows:

·       loading starts as false (i.e., not loading).

·       error starts as null (i.e., no error by default).

·       data starts as null (i.e., no data).

 

Fetching Logic (fetchData)

The fetchData function is an async function that performs the actual data fetching using the fetch API:

·       Set Loading to true: Before starting the request, the loading state is set to true to indicate that the fetch process is in progress.

·       Perform the Fetch: The fetch function is called with the provided url.

o   If the response is not okay (response.ok is false), it sets an error state with a generic error message.

o   If the response is okay, the JSON data is extracted and stored in the data state.

·       Error Handling: If any error occurs during the fetch (e.g., network issues), it is caught in the catch block and stored in the error state.

·       Set Loading to false: Regardless of success or failure, loading is set to false in the finally block to indicate that the fetch process is complete.

 

Effect Hook (useEffect)

The useEffect hook is used to trigger the fetchData function whenever the url changes:

·       It logs the triggering of the URL and then calls fetchData to initiate the data fetching process.

·       The dependency array [url] ensures that the fetch operation is re-triggered only when the url changes. If the url remains the same, the hook does not re-run.

 

Return Values

The hook returns an object with the following properties:

·       loading: The current loading state.

·       error: Any error that occurred during the fetch process.

·       data: The data retrieved from the fetch request.

This allows a React component that uses useFetch to easily manage and display the loading state, any errors, and the fetched data.

 

Step 4: Create components folder in src folder and define ImageLoader component.

 

ImageLoader.jsx

import { useEffect, useState, useRef } from "react";
import useFetch from "../hooks/useFetch";

const urlToFetch = "https://picsum.photos/v2/list?page={PAGE_NUMBER}&limit=10";

export default function ImageLoader() {
  const [fullImages, setFullImages] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const url = urlToFetch.replace("{PAGE_NUMBER}", pageNumber);
  const { loading, error, data } = useFetch(url);

  // Update fullImages when new data is fetched
  useEffect(() => {
    if (data && data.length > 0) {
      setFullImages((prevImages) => [...prevImages, ...data]);
    }
  }, [data]); // Only run this effect when data changes

  return (
    <div>
      {loading && <div className="loading">Loading Is In Progress.....</div>}

      {error && (
        <div className="error">Error Occurred While Fetching Images....</div>
      )}

      {fullImages.length > 0 && (
        <div className="imagesContainer">
          {fullImages.map((image, index) => (
            <img
              src={image.download_url}
              alt={image.id}
              key={index}
              width="200"
              height="200"
            />
          ))}
        </div>
      )}

      <button
        onClick={() => {
          setPageNumber((prevPageNumber) => prevPageNumber + 1);
        }}
      >
        Load More Images
      </button>
    </div>
  );
}

Step 5: Go to the project root folder and execute following commands.

npm install
npm run dev

Click on ‘Load More Images’ button to load more images.

You can download the Application from this link.



Previous                                                    Next                                                    Home

height: auto in CSS: How It Works and Why It's Essential for Responsive Design

In CSS, setting height: auto makes the height of an element automatically adjust based on its content. The auto value is the default for the height property, and it tells the browser to calculate the element’s height based on the content inside, without a fixed or specific measurement.

 

How height: auto Works?

When you set height: auto, the browser calculates the element's height based on:

·       Content height: The element will expand vertically to fit all its child content.

·       Padding and borders: If you add padding or borders, the height of the element will adjust accordingly.

·       Parent container constraints: If there are any constraints from parent containers, the element will resize within those bounds.

 

Benefits of height: auto

1.   Responsive Layouts: height: auto is commonly used in responsive web design because it allows the content to expand or shrink based on the viewport and device size, ensuring content is displayed as intended across different screens.

2.   Automatic Content Adjustment: Elements like images, paragraphs, or containers will expand to fit whatever content is inside them, which is helpful when the content can vary in size.

3.   Overflow Handling: For containers with dynamic content (like user-generated content), height: auto prevents content overflow by expanding the container automatically as needed.

4.   Ease of Maintenance: It reduces the need to set fixed heights, making layouts easier to maintain and adaptable to changes in content.

 

Example

container {
  width: 100%;
  height: auto; /* adjusts to fit content */
  padding: 20px;
  background-color: lightgrey;
}

 

In this example, .container will automatically adjust its height to fit any content added within it, plus the 20px padding on all sides.

 

Common Use Cases

·       Images: Ensuring images maintain aspect ratio with height: auto when setting width in a responsive layout.

·       Text Containers: Allowing paragraphs or divs to expand vertically based on text length.

·       Dynamic Components: Great for sections with expandable/collapsible content, like accordions.

 

Using height: auto is particularly helpful for creating fluid layouts that adapt to content, helping keep your design flexible and user-friendly.

 

Previous                                                    Next                                                    Home

colgroup Tag in HTML: Efficiently Grouping, Styling and Managing Table Columns

The <colgroup> tag in HTML is used to group one or more column within a table. By grouping columns together, you can apply consistent styling to multiple columns at once, such as setting their width or background color. You can set attributes like width for columns within a group, which simplifies managing tables with many columns.

Example

<table>
    <colgroup>
        <col span="2" style="background-color: hsl(69, 88%, 87%); width: 100px;">
        <col style="background-color: #c8fe63; width: 150px;">
    </colgroup>
</table>

1.   <colgroup>: Groups and styles columns in a table, allowing for easier management and application of attributes to multiple columns.

2.   <col>: Defines specific properties for individual columns within the <colgroup>.

 

column-group.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Column Group Example</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;
        }
        
        tfoot > tr > td{
            text-align: center;
        }
    </style>
</head>
<body>

    <h1>colgroup Demo</h1>

    <table>
        <colgroup>
            <col span="2" style="background-color: hsl(69, 88%, 87%); width: 100px;">
            <col style="background-color: #c8fe63; width: 150px;">
          </colgroup>

        <caption>Employees Of ABC Corporation</caption>

        <thead>
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
          </tr>
        </thead>
      
        <tbody>
          <tr>
            <td>Rama Krishna</td>
            <td>36</td>
            <td>Principle Engineer</td>
          </tr>
          <tr>
            <td>Abhishek Ramesh</td>
            <td>32</td>
            <td>Frontend Engineer</td>
          </tr>
        </tbody>

      </table>
      
</body>
</html>

   

Previous                                                    Next                                                    Home