πŸ”’ 8. Lists and Keys in React & πŸ“ 9. Forms in React

Payal PorwalPayal Porwal
12 min read

πŸ”Έ What is a List in React?

In real life, we often deal with lists:

  • A list of tasks (To-do app)

  • A list of users

  • A list of products

In React, we can display lists of data dynamically using JavaScript’s .map() method.


πŸ”Ή Why .map()?

JavaScript’s .map() method lets you loop over an array and return JSX for each item.

🧠 In React, .map() is the best way to render multiple items from an array into the UI.


βœ… Basic Example: List of Fruits

Let’s create a simple list of fruits and render them:

import React from 'react';

function FruitList() {
  const fruits = ['Apple', 'Banana', 'Orange', 'Mango'];

  return (
    <div>
      <h2>Fruit List πŸ‰</h2>
      <ul>
        {fruits.map((fruit, index) => (
          <li key={index}>{fruit}</li>
        ))}
      </ul>
    </div>
  );
}

export default FruitList;

πŸ” What’s Happening Here?

LineExplanation
fruitsArray of fruit names
.map()Loops through each fruit
<li key={index}>Displays each fruit in the list
key={index}Gives each item a unique identity (more on this below)

🧠 What is a key in React?

React uses the key prop to track which item has changed, added, or removed.

πŸ”‘ Why is key important?

If you don’t use a proper key:

  • React will re-render all list items unnecessarily.

  • It can lead to performance issues and bugs.


πŸ”” Rules for Using key:

  1. Must be unique among siblings

  2. Avoid using array index as key (if the list can change)

  3. Use a unique id (if available)


βœ… Real-Life Example: List of Users (with id as key)

import React from 'react';

function UserList() {
  const users = [
    { id: 1, name: 'Aman' },
    { id: 2, name: 'Priya' },
    { id: 3, name: 'Ravi' },
  ];

  return (
    <div>
      <h2>Users</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>Hello, {user.name}!</li>
        ))}
      </ul>
    </div>
  );
}

export default UserList;

πŸ’¬ Output:

Users
- Hello, Aman!
- Hello, Priya!
- Hello, Ravi!

πŸ’‘ Tips for Working Professionals:

  • Always try to use a database ID or a unique slug/uuid for keys.

  • Avoid using index as a key if you’re modifying the list (e.g. deleting, reordering).

  • Keys help with performance when your app gets large and dynamic.


βœ… Bonus Example: Rendering Components from List

You can also render custom components inside a map:

function User({ name }) {
  return <p>Welcome, {name} πŸ‘‹</p>;
}

function UserList() {
  const names = ['Raj', 'Simran', 'Dev'];

  return (
    <div>
      {names.map((n, i) => (
        <User key={i} name={n} />
      ))}
    </div>
  );
}

🧩 Real Use Cases in Projects:

Use CaseExample
BlogRendering list of posts
E-commerceList of products
DashboardUser or task list
MessagingChat list
DropdownsDynamic options

πŸ“Œ Summary:

βœ… .map() is used to loop through arrays and render JSX
βœ… key helps React optimize re-renders
βœ… Always use a unique key (preferably ID)
βœ… Lists are used everywhere in real-world apps.


FAQs :

πŸ”Ή Q1: Hum key ka use React me hi kyu karte hain? JavaScript (JS) me kyu nahi?

βœ… Answer:

JavaScript (JS) sirf data ko process karta hai β€” usse render nahi karta.

Lekin React ka kaam hai UI (User Interface) banana aur update karna, aur jab bhi koi data change hota hai (like list me naya item add ya remove), React ko ye decide karna padta hai ki kya badla hai aur kya re-render karna hai.

πŸ‘‰ Is decision ko asaan banane ke liye hi React me key ka use hota hai.

πŸ” Example samjho:

Agar tumhare paas ek list of users hai, aur tum usme se ek user delete kar do, to React ko ye pata hona chahiye ki kaunsa user remove hua hai β€” isiliye har item ko ek key milti hai (jaise id), jo usse uniquely identify karta hai.

🧠 JavaScript me aisa kuch nahi hota, kyunki wo khud se UI update nahi karta β€” wo sirf data store ya manipulate karta hai.


πŸ“Œ Short Summary:

ReactJavaScript
UI manage karta haiSirf data manage karta hai
Efficient updates ke liye key chahiyekey ki zarurat nahi
key help karta hai React ko re-render optimize karne meJS me rendering hoti hi nahi

πŸ”Ή Q2: "JS me rendering hoti hi nahi" β€” kya yeh sahi hai?

βœ… Short Answer:

JS khud se rendering nahi karta.
Lekin DOM ko update karne ke liye JS ka use hota hai, toh indirectly JS "rendering" me help karta hai.


πŸ” Thoda detail me:

πŸ”Έ JavaScript ek programming language hai jo data ko handle karta hai.
Lekin woh UI render karne ka kaam directly nahi karta. Uske liye hum DOM APIs (like document.createElement, innerHTML, etc.) ka use karte hain.

πŸ’‘ Example:

jsCopyEditdocument.getElementById("root").innerHTML = "<h1>Hello World</h1>";

Yahaan JS ne UI update kiya, lekin yeh kaam usne manually DOM ke through kiya. Har baar tumhe pura HTML likhna padta hai.
No automatic re-rendering!


βš›οΈ React me kya hota hai?

React khud se UI ko render aur re-render karta hai automatically, jab:

  • state ya props change hoti hain.

React Virtual DOM ka use karta hai, jisse changes detect hote hain aur sirf wahi part update hota hai β€” aur yahan key ka role aata hai.


πŸ” Final Verdict:

FeaturePlain JavaScriptReact
RenderingManually (via DOM)Automatically (via JSX + Virtual DOM)
Re-renderingDeveloper handles it manuallyHandled automatically
Key required?❌ Nahiβœ… Haan (for lists)

πŸ”Ή Q3: React me return kya hota hai?

βœ… Short Answer:

React me return ka use component ka UI define karne ke liye hota hai.

Jab bhi koi React component banta hai (function ya class), uske andar return() likhte hain jisme JSX hota hai.
Ye JSX browser me HTML me convert ho kar show hota hai.


πŸ” Example:

jsxCopyEditfunction Greeting() {
  return (
    <h2>Good Morning! β˜€οΈ</h2>
  );
}

βš™οΈ Isme kya ho raha hai?

  • Greeting ek React Functional Component hai

  • return() ke andar jo bhi JSX diya gaya hai β€” wahi screen pe render hoga

Agar tum return hata doge, to component kuch show hi nahi karega.


πŸ”„ Compare with JS function:

Normal JS function:

jsCopyEditfunction add(a, b) {
  return a + b; // returns value
}

React function:

jsxCopyEditfunction App() {
  return <h1>Hello from React</h1>; // returns JSX (UI)
}

🧠 React me return = "Show this UI on screen"


πŸ”š Summary:

πŸ”‘ Key Points:

  • Plain JavaScript manually UI render karta hai using DOM methods

  • React automatically re-render karta hai on state/prop changes

  • React me return is used to define what should be shown on the screen

πŸ“ 9. Forms in React


πŸ”Έ What are Forms?

A form is used to collect user input like:

  • Name

  • Email

  • Password

  • Feedback

In plain HTML, form inputs like <input>, <textarea> work directly. But in React, we control the values using state. This makes them controlled components.


πŸ”Ή Controlled vs Uncontrolled Components

TermControlled ComponentUncontrolled Component
Input ValueControlled by React (via useState)Controlled by DOM
Data HandlingStored in component stateAccessed using ref
Recommended?βœ… Yes (standard in React)❌ Use only in rare cases

🎯 React encourages using Controlled Components for better control, validation, and consistency.


βœ… Controlled Component Example

Let’s make a simple form to collect a user’s name and email.

import React, { useState } from 'react';

function ContactForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  function handleSubmit(e) {
    e.preventDefault(); // stop form from refreshing the page
    alert(`Thank you ${name}, we will contact you at ${email}`);
    setName('');
    setEmail('');
  }

  return (
    <form onSubmit={handleSubmit}>
      <h2>Contact Us</h2>

      <label>Name:</label>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter your name"
      />

      <br />

      <label>Email:</label>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Enter your email"
      />

      <br />

      <button type="submit">Submit</button>
    </form>
  );
}

export default ContactForm;

πŸ” Explanation:

LineMeaning
useState('')To store form data
value={name}Binds input to state
onChange={(e) => setName(e.target.value)}Updates state on every keystroke
e.preventDefault()Prevents page refresh
alert(...)Displays a message using form data

🧠 What's event.target.value?

It's the current value of the input field. React uses it inside onChange to update the state.

Example:

<input onChange={(e) => setName(e.target.value)} />

Here:

  • e is the event object.

  • e.target is the input field.

  • e.target.value is the text entered by the user.


βœ… Bonus: Multiple Inputs with One State Object

Sometimes forms have many fields. You can use a single state object to handle them.

function RegisterForm() {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: ''
  });

  function handleChange(e) {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value
    }));
  }

  function handleSubmit(e) {
    e.preventDefault();
    console.log(formData);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="username" value={formData.username} onChange={handleChange} placeholder="Username" />
      <input name="email" value={formData.email} onChange={handleChange} placeholder="Email" />
      <input name="password" type="password" value={formData.password} onChange={handleChange} placeholder="Password" />
      <button type="submit">Register</button>
    </form>
  );
}

🧠 Line-by-line Explanation:

🟩 function handleChange(e)

Ye function har input ke onChange par chalega.
e = event object = jisme wo input field ki info hoti hai jisme user ne typing ki.


🟩 const { name, value } = e.target;

Ye line input box ke name aur value ko extract kar rahi hai.

Maan lo email box par type ho raha hai:

<input name="email" value={formData.email} />

To:


🟩 setFormData((prev) => ({ ...prev, [name]: value }))

Let's break it πŸ”

🟒 prev:

Ye formData ka old value hai (previous state).

🟒 ...prev:

Iska matlab: old data ko as-it-is rakho.

🟒 [name]: value:

Update karo jo field currently update ho rahi hai.
Yaha name dynamically change ho raha hai based on which input triggered the event.

So agar:

To updated object banega:

{
  username: '',        // unchanged
  email: 'john@gmail.com',  // updated
  password: ''         // unchanged
}

βœ… Final Result:

Har baar jab koi input mein type karega:

  • React formData ko update karega

  • Sirf wahi field update hogi jo change ho rahi hai

  • Baaki data safe rahega


πŸ“Œ Summary

βœ… Forms in React are mostly Controlled Components
βœ… Use useState() to manage form input values
βœ… onChange updates the state
βœ… onSubmit handles the form logic
βœ… event.target.value gives you the input value
βœ… You can use a single state object for big forms


πŸ“ Mini Project: Feedback Collector App

Let's build a real-life mini project in React that combines:

  • βœ… Forms (user input)

  • βœ… Lists (displaying entered data)

  • βœ… Bootstrap (for styling)

  • βœ… React Concepts: useState, event handling, controlled components, list rendering with map, and key props.

🎯 Project Goal:

Create a simple app where users can submit feedback with their name, email, and comment.
Submitted feedback is shown in a list format below the form.


πŸ“¦ Concepts Covered in This Project:

React ConceptUsed in this Project?
useState Hookβœ… Yes (to manage form and list data)
Controlled Componentsβœ… Yes (to handle form input values)
Form Handlingβœ… Yes (submit + validation)
List Rendering (map)βœ… Yes (to show feedback entries)
Key Prop in mapβœ… Yes
Bootstrap Stylingβœ… Yes (form + list cards)

πŸ”§ Step-by-step Implementation

1. Setup Project

npx create-react-app feedback-app
cd feedback-app
npm install bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';

3. Project Folder Structure

/src
  └── App.js
  └── FeedbackForm.js
  └── FeedbackList.js

4. App.js (Main File)

import React, { useState } from 'react';
import FeedbackForm from './FeedbackForm';
import FeedbackList from './FeedbackList';
import './App.css';

function App() {
  const [feedbacks, setFeedbacks] = useState([]);

  const addFeedback = (newFeedback) => {
    setFeedbacks([newFeedback, ...feedbacks]);
  };

  return (
    <div className="container mt-5">
      <h1 className="text-center mb-4">πŸ’¬ Feedback Collector</h1>
      <FeedbackForm addFeedback={addFeedback} />
      <hr />
      <FeedbackList feedbacks={feedbacks} />
    </div>
  );
}

export default App;

5. FeedbackForm.js

import React, { useState } from 'react';

function FeedbackForm({ addFeedback }) {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    comment: ''
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    if (!formData.name || !formData.email || !formData.comment) {
      alert('Please fill all fields');
      return;
    }

    addFeedback(formData);
    setFormData({ name: '', email: '', comment: '' });
  };

  return (
    <form className="card p-4 shadow" onSubmit={handleSubmit}>
      <h4>πŸ“ Submit Feedback</h4>

      <div className="mb-3">
        <label>Name</label>
        <input
          name="name"
          className="form-control"
          value={formData.name}
          onChange={handleChange}
          placeholder="Your Name"
        />
      </div>

      <div className="mb-3">
        <label>Email</label>
        <input
          name="email"
          type="email"
          className="form-control"
          value={formData.email}
          onChange={handleChange}
          placeholder="Your Email"
        />
      </div>

      <div className="mb-3">
        <label>Comment</label>
        <textarea
          name="comment"
          className="form-control"
          value={formData.comment}
          onChange={handleChange}
          placeholder="Your Feedback"
        />
      </div>

      <button className="btn btn-primary">Submit</button>
    </form>
  );
}

export default FeedbackForm;

6. FeedbackList.js

import React from 'react';

function FeedbackList({ feedbacks }) {
  return (
    <div className="mt-4">
      <h4>πŸ“‹ Feedback Received</h4>
      {feedbacks.length === 0 && <p>No feedback yet...</p>}
      {feedbacks.map((fb, index) => (
        <div key={index} className="card mb-3 shadow-sm">
          <div className="card-body">
            <h5>{fb.name}</h5>
            <p><strong>Email:</strong> {fb.email}</p>
            <p>{fb.comment}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

export default FeedbackList;

7. CSS (Optional for small tweaks) – App.css

body {
  background-color: #f8f9fa;
}

βœ… Output Overview

  • User fills form ➝ submits feedback

  • That feedback appears below in a stylish Bootstrap card

  • All done using React forms + list rendering


πŸš€ If you want:

  • πŸ”— GitHub-ready structure

  • πŸ“ Assignment based on these

  • πŸ’‘ More project ideas using other React topics (like Props, State, Lists, Hooks)

Just say the word! in below comment section .

πŸ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant React notes, tutorials, and project ideas β€”
πŸ“© Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment,
πŸŽ₯ Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. πŸš€

0
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟