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

Returning values from a function in JavaScript

Functions can return a value using the return statement. This allows you to capture the result of a function and use it elsewhere in your code.

returnValueFromFunction.js

function add(a, b) {
    return a + b;
}

let a = 5;
let b = 3;
let sum = add(5, 3);

console.log(`Sum of ${a} and ${b} is ${sum}`);

Output

Sum of 5 and 3 is 8

In this example,

1.   The add function takes two parameters, a and b.

2.   It returns the sum of a and b.

3.   The returned value is stored in the sum variable.

 

  

Previous                                                    Next                                                    Home

Mastering the background-size Property in CSS: A Comprehensive Guide to Perfecting Your Background Images

The background-size property in CSS is used to specify the size of the background image of an element. It allows you to control how the background image is scaled or resized to fit within the element's background area.

Syntax

background-size: value;

 

How to specify background size value?

The background-size property accepts several values, each serving different purposes.

 

1. auto: The background image retains its original size. This is the default value. The image will be displayed at its intrinsic size, without any scaling.

background-size: auto;

2. length

You can specify the width and height of the background image using units like pixels (px), ems (em), percentages (%), etc.,

 

If you specify one value, it will set the width, and the height will automatically scale to maintain the aspect ratio.

 

If you specify two values (e.g., width height), the image will be scaled to those specific dimensions.

background-size: 100px 50px;
background-size: 100px auto;

3. percentage

You can specify the size of the background image relative to the containing element.

 

If you specify one percentage, it will set the width relative to the element's width, and the height will auto-scale.

 

If you specify two percentages (e.g., width height), the image will scale according to those relative dimensions.

background-size: 50% 50%;
background-size: 100% auto;

4. cover

The background image will scale to cover the entire area of the element while maintaining its aspect ratio. The image may be cropped if the aspect ratio of the image does not match the aspect ratio of the element.

background-size: cover;

5. contain

The background image will scale to the largest size that fits within the element's background area while maintaining its aspect ratio.  The entire image will be visible, but there may be gaps or empty space if the aspect ratios differ.

 

The entire image will be visible, but there may be gaps or empty space if the aspect ratios differ.

 

greenary.jpg


 

backgroundSize.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Background-Size Property Examples</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }
        .container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .box {
            border: 2px solid #333;
            background-image: url('../../images/greenary.jpg');
            background-repeat: no-repeat;
            height: 200px;
            position: relative;
        }
        .box span {
            position: absolute;
            bottom: 10px;
            left: 10px;
            background-color: rgba(0, 0, 0, 0.7);
            color: #fff;
            padding: 5px;
            font-size: 14px;
        }
        /* Examples */
        .auto {
            background-size: auto;
        }
        .length {
            background-size: 100px 50px;
        }
        .length-auto {
            background-size: 100px auto;
        }
        .percent {
            background-size: 50% 50%;
        }
        .contain {
            background-size: contain;
        }
        .cover {
            background-size: cover;
        }
    </style>
</head>
<body>

    <h1>Examples of CSS Background-Size Property</h1>
    <div class="container">
        <div class="box auto">
            <span>background-size: auto;</span>
        </div>
        <div class="box length">
            <span>background-size: 100px 50px;</span>
        </div>
        <div class="box length-auto">
            <span>background-size: 100px auto;</span>
        </div>
        <div class="box percent">
            <span>background-size: 50% 50%;</span>
        </div>
        <div class="box contain">
            <span>background-size: contain;</span>
        </div>
        <div class="box cover">
            <span>background-size: cover;</span>
        </div>
    </div>

</body>
</html>

Open ‘backgroundSize.html’ in a browser, you will see below kind of screen.

  

Previous                                                    Next                                                    Home

HTML Lists: A Beginner's Guide to Ordered, Unordered, and Definition Lists

In HTML, there are three main types of lists we can use.

1.   Ordered Lists (<ol>)

2.   Unordered Lists (<ul>)

3.   Definition Lists (<dl>)

 

Ordered Lists

Use an ordered list when the sequence of items is important, such as instructions or steps in a process. Items are numbered automatically (1, 2, 3, etc.), but you can also use different types of numbering (e.g., letters or Roman numerals) with CSS.

 

Example

<ol>
  <li>Wake up</li>
  <li>Have breakfast</li>
  <li>Go to College</li>
  <li>Attend classes</li>
  <li>Go to play area and play</li>
  <li>Back to home</li>
  <li>Have dinner</li>
  <li>Sleep well</li>
</ol>

·      <ol>: This is the container element for the ordered list.

·      <li>: Each item within the list is wrapped in a <li> (list item) tag.

 

ordered-list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ordered List Example</title>
</head>
<body>
    
    <ol>
        <li>Wake up</li>
        <li>Have breakfast</li>
        <li>Go to College</li>
        <li>Attend classes</li>
        <li>Go to play area and play</li>
        <li>Back to home</li>
        <li>Have dinner</li>
        <li>Sleep well</li>
      </ol>
      
</body>
</html>


 

Unordered List

Use an unordered list when the sequence of items is not important, such as a list of ingredients or features. Items are marked with bullet points, but you can change the bullet style (e.g., circles, squares) using CSS.

 

Example

<ul>
  <li>Apples</li>
  <li>Bananas</li>
  <li>Cherries</li>
</ul>

·      <ul>: This is the container element for the unordered list.

·      <li>: Each item within the list is wrapped in a <li> tag.

 

unordered-list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Unordered List Example</title>
</head>
<body>
    
    <ul>
        <li>Apples</li>
        <li>Bananas</li>
        <li>Cherries</li>
        <li>Grapes</li>
        <li>Berries</li>
        <li>Mangoes</li>
    </ul>
      
</body>
</html>

 


 

Definition Lists (<dl>)

Use a definition list for pairs of terms and their descriptions, such as a glossary or a list of terms with definitions. In general, terms are aligned to the left, and their definitions are indented under them.

 

 Example

<dl>
  <dt>HTML</dt>
  <dd>HyperText Markup Language</dd>
  <dt>CSS</dt>
  <dd>Cascading Style Sheets</dd>
  <dt>HTTP</dt>
  <dd>Hypet Text Transfer Protocol</dd>
</dl>

·      <dl>: This is the container element for the definition list.

·      <dt>: Each term is wrapped in a <dt> (definition term) tag.

·      <dd>: Each definition corresponding to a term is wrapped in a <dd> (definition description) tag.

 

definition-list.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Definition List Example</title>
</head>
<body>
    
    <dl>
        <dt>HTML</dt>
        <dd>HyperText Markup Language</dd>
        <dt>CSS</dt>
        <dd>Cascading Style Sheets</dd>
        <dt>HTTP</dt>
        <dd>Hypet Text Transfer Protocol</dd>
    </dl>
      
</body>
</html>

 


 

  

Previous                                                    Next                                                    Home