Monday, 2 December 2024

Mastering HTML Links: An In-Depth Look at the "a" Tag

The <a> (anchor) tag in HTML is used to create hyperlinks, which are essential for navigating between different web pages or sections within a web page. It can also be used to link to resources such as files, email addresses, or other URLs.

Syntax

<a href="URL">Link Text</a>

Following table summarizes the key attributes of anchor tag.

 

Attribute

Description

href

This attribute specifies the URL of the page or resource the link goes to. It is the most important attribute of the <a> tag. If href is not present, the <a> tag will not be a hyperlink.

target

This attribute specifies where to open the linked document. Common values include,

 

1.   _self (default): Opens the link in the same frame or window as the current page.

2.   _blank: Opens the link in a new tab or window.

3.   _parent: Opens the link in the parent frame.

4.   _top: Opens the link in the full body of the window, breaking out of any frames.

title

This attribute provides additional information about the link. When a user hovers over the link, the text in the title attribute will be displayed as a tooltip.

download

This attribute suggests that the browser should download the resource rather than navigate to it. It can specify a filename for the downloaded file.

rel

This attribute specifies the relationship between the current document and the linked document. Common values include nofollow, noopener, and noreferrer.

 

The nofollow value is used to instruct search engines not to follow the link. This means that the search engine crawlers will not pass any "link juice" or ranking power to the linked page. It is often used to prevent endorsement or to avoid linking to untrusted or user-generated content.

 

The noopener value is used to prevent the newly opened tab or window from having control over the original tab or window. This is a security feature to prevent malicious scripts on the linked page from using the window.opener object to access and potentially manipulate the original page.

 

The noreferrer value prevents the browser from sending the HTTP referrer header to the linked site. This means that the destination website will not know from which site the visitor has come. It also includes the functionality of noopener, enhancing security by preventing access to the window.opener object.

hreflang

Specifies the language of the linked document. It's useful for search engines to understand the language of the destination page.

type

Specifies the MIME type of the linked document.

 

Example 1: Basic Hyperlink

<a href="https://self-learning-java-tutorial.blogspot.com">Programming Languages Tutorial</a>

This is a standard hyperlink. When the user clicks on the text "Programming Languages Tutorial," it will navigate them to the URL https://self-learning-java-tutorial.blogspot.com in the same browser tab or window.

 

Example 2: Hyperlink that Opens in a New Tab

<a href="https://self-learning-java-tutorial.blogspot.com" target="_blank">Programming Languages Tutorial (Open in new tab)</a>

This link behaves like the previous one but includes the target="_blank" attribute. This attribute instructs the browser to open the link in a new tab or window, allowing the user to stay on the current page while also visiting the linked site.

 

Example 3: Link with Tooltip

<a href="https://self-learning-java-tutorial.blogspot.com" title="Click to visit tutorials website">Programming Languages Tutorial</a>

This link includes a title attribute. When a user hovers over the link text "Programming Languages Tutorial," a tooltip with the text "Click to visit tutorials website" will appear, providing additional information about the link.

 

Example 4: Downloadable Link

<a href="files/apache-licence.pdf" download="apache-licence.pdf">Download Apache Licence PDF</a>

This link is intended for downloading a file rather than navigating to it. The href attribute points to the file location files/apache-licence.pdf, and the download attribute suggests the file name to save as (apache-licence.pdf). When clicked, the browser will prompt the user to download the file rather than open it.

 

Example 5: Link to an Email Address

<a href="mailto:someone@example.com">Send Email</a>

This link uses the mailto: scheme, which will open the user's default email client with a new email message addressed to someone@example.com. Clicking this link allows users to easily send an email.

 

Example 6: Link to a Phone Number

<a href="tel:+1234567890">Call Us Now</a>

The tel: scheme is used for telephone links. When clicked on a device that supports calling (like a smartphone), it will initiate a phone call to the number +1234567890.

 

Example 7: Link to a Page within the Same Server

<a href="about-me.html">About Me</a>

This link points to a local page called about-me.html. It is a relative link, meaning it is assumed to be on the same server as the current page. When clicked, it navigates the user to the specified page within the same domain.

 

Each of these links uses the <a> (anchor) tag, with the href attribute specifying the destination. Depending on additional attributes like target, title, download, mailto:, or tel:, the behavior of the link changes, providing more functionality than just simple navigation.

 

hyper-link-demo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hyperlink Demo</title>

    <style>
        div {
            margin: 10px;
        }

        /* Basic anchor link style */
        a {
            background-color: lightgray;
            color: #3498db; /* Default link color */
            text-decoration: none; /* Removes the underline */
            font-weight: 500; /* Makes the text slightly bold */
            transition: color 0.3s ease, text-decoration 0.3s ease; /* Smooth transition for hover effects */
        }

        /* Hover state: changes when the user hovers over the link */
        a:hover {
            color: #2c3e50; /* Darker shade on hover */
            text-decoration: underline; /* Adds underline on hover for emphasis */
        }

        /* Active state: changes when the link is being clicked */
        a:active {
            color: #2980b9; /* Slightly different color to indicate click */
        }

        /* Visited state: changes for links that have been visited */
        a:visited {
            color: #8e44ad; /* Different color for visited links */
        }

        /* Focus state: changes when the link is focused via keyboard or mouse click */
        a:focus {
            outline: 2px solid #2980b9; /* Adds a blue outline for accessibility */
            outline-offset: 2px; /* Moves the outline slightly away from the text */
        }

    </style>
</head>
<body>
    <!-- This link will navigate to https://self-learning-java-tutorial.blogspot.com when clicked. -->
    <div><a href="https://self-learning-java-tutorial.blogspot.com">Programming Languages Tutorial</a></div>

    <!-- This link will open the https://self-learning-java-tutorial.blogspot.com website in a new tab or window. -->
    <div><a href="https://self-learning-java-tutorial.blogspot.com" target="_blank">Programming Languages Tutorial (Open in new tab)</a></div>

    <!-- Link with tooltip -->
    <div><a href="https://self-learning-java-tutorial.blogspot.com" title="Click to visit tutorials website">Programming Languages Tutorial</a></div>

    <!-- This link will download the apache-licence.pdf file instead of navigating to it. -->
    <div><a href="files/apache-licence.pdf" download="apache-licence.pdf">Download Apache Licence PDF</a></div>

    <!-- Link to an email address -->
    <div><a href="mailto:someone@example.com">Send Email</a></div>

    <!-- Link to phone number -->
    <div><a href="tel:+1234567890">Call Us Now</a></div>

    <!-- Link to a page with in the same server -->
    <div><a href="about-me.html">About Me</a></div>

</body>
</html>

 

Previous                                                    Next                                                    Home

Sunday, 1 December 2024

Building a Simple Editable UserInfo Page in React

In this post, I am going to explain the how to create a simple functional UserInfo page using React. This page will allow users to view and edit their personal details, such as their name, email, and age, all within an interactive interface.

I am going to use following techniques to build this page.

 

1.   State Management: Manage the user information with React's useState hook to store and update user details dynamically.

2.   Conditional Rendering: Used to toggle between edit and view modes, enabling users to switch seamlessly between viewing their information and editing it.

 

By the end of this tutorial, you will have a fully functional UserInfo page that not only displays user details but also allows users to edit and save changes effortlessly.

 

Define user component

export default function User({ user }) {

 

Here, we define the User component, which takes a user prop. This prop represents the initial user information we will display and allow editing for.

 

State Management

const [userInfo, setUserInfo] = useState(user);
const [isEditing, setIsEditing] = useState(false); // Default to non-edit mode

 

We use two pieces of state here,

1.   userInfo: This holds the current user details, initialized with the user prop.

2.   isEditing: This boolean state tracks whether the component is in edit mode. It starts as false, meaning the user details are displayed in a read-only format.

 

Saving User Details

function saveUserDetails(event) {
    event.preventDefault();
    setIsEditing(false); // Switch back to view mode after saving
    // Add logic to persist data if necessary
}

 

The saveUserDetails function handles the form submission. It prevents the default behavior of the form (which would typically cause a page refresh) and switches the state back to view mode. Here, you can also add logic to persist the user data, such as sending it to a server or saving it locally.

 

Conditional Rendering of User Info

 

const contentToDisplay = isEditing ? (
    <>
        {/* Editable fields for user information */}
    </>
) : (
    <>
        {/* Display user information */}
    </>
);

 

The contentToDisplay variable uses a ternary operator to conditionally render either editable input fields or the read-only user information based on the isEditing state:

 

1.   If isEditing is true, input fields for the username, email, and age are rendered, allowing users to modify their details.

2.   If isEditing is false, the user's current information is displayed.

 

Handling Input Changes

Inside the editable section, we use onChange handlers for each input field. Following snippet highlight the onChange event handler for username text field.

onChange={(event) => setUserInfo({
    ...userInfo, 
    name: event.target.value,
})}

 

These handlers update the corresponding property in the userInfo state whenever the user types into the input fields. The spread operator (...userInfo) ensures that other properties remain unchanged.

 

Rendering the Form

return (
    <form onSubmit={saveUserDetails}>
        {contentToDisplay}
        <br />
        <button type="button" onClick={() => setIsEditing(!isEditing)}>
            {isEditing ? "Save" : "Edit"}
        </button>
    </form>
);

 

Finally, the return statement renders the form containing contentToDisplay and a button that toggles between "Edit" and "Save." The button's onClick event calls a function to switch the isEditing state, allowing users to enter or save their changes.

 

Follow below step-by-step procedure to build the complete working application.

 

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

 

Project structure looks like below.

 


 

Step 2: Create components folder in src/ folder and define User component.

 

User.jsx

 

import { useState } from "react";

export default function User({ user }) {
    const [userInfo, setUserInfo] = useState(user);
    const [isEditing, setIsEditing] = useState(false); // Default to non-edit mode

    // Save user details or handle form validation
    function saveUserDetails(event) {
        event.preventDefault();
        setIsEditing(false); // Switch back to view mode after saving
        // Add logic to persist data if necessary
    }

    // JSX for displaying or editing user info
    const contentToDisplay = isEditing ? (
        <>
            <label>Username : </label>
            <input
                type="text"
                value={userInfo.name}
                onChange={(event) => setUserInfo({
                    ...userInfo, 
                    name: event.target.value,
                })}
            />
            <br />
            <label>Email : </label>
            <input
                type="email"
                value={userInfo.email}
                onChange={(event) => setUserInfo({
                    ...userInfo, 
                    email: event.target.value,
                })}
            />
            <br />
            <label>Age : </label>
            <input
                type="text"
                value={userInfo.age}
                onChange={(event) => setUserInfo({
                    ...userInfo, 
                    age: event.target.value,
                })}
            />
            <br />
        </>
    ) : (
        <>
            <label>Username : {userInfo.name}</label>
            <br />
            <label>Email : {userInfo.email}</label>
            <br />
            <label>Age : {userInfo.age}</label>
            <br />
        </>
    );

    return (
        <form onSubmit={saveUserDetails}>
            {contentToDisplay}
            <br />
            {/* Toggle between Edit and Save button */}
            <button type="button" onClick={() => setIsEditing(!isEditing)}>
                {isEditing ? "Save" : "Edit"}
            </button>
        </form>
    );
}

Step 3: Update main.jsx like below.

 

main.jsx

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

const userDetails = {
  name: "Krishna",
  age: 34,
  email: "krishna@abc.com",
};

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <User user={userDetails} />
  </StrictMode>
);

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

  cd editable_user
  npm install
  npm run dev

Open the url ‘http://localhost:5173/’ in browser, you will see below screen.



Click on Edit button to update the user information.


 

You can download this Application from this link.

Previous                                                    Next                                                    Home