π’ 8. Lists and Keys in React & π 9. Forms in React

Table of contents
- πΈ What is a List in React?
- πΉ Why .map()?
- β Basic Example: List of Fruits
- π§ What is a key in React?
- π Rules for Using key:
- β Real-Life Example: List of Users (with id as key)
- π‘ Tips for Working Professionals:
- β Bonus Example: Rendering Components from List
- π§© Real Use Cases in Projects:
- π Summary:
- FAQs :
- π 9. Forms in React
- π Mini Project: Feedback Collector App
πΈ 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?
Line | Explanation |
fruits | Array 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
:
Must be unique among siblings
Avoid using array index as key (if the list can change)
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 Case | Example |
Blog | Rendering list of posts |
E-commerce | List of products |
Dashboard | User or task list |
Messaging | Chat list |
Dropdowns | Dynamic 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:
React | JavaScript |
UI manage karta hai | Sirf data manage karta hai |
Efficient updates ke liye key chahiye | key ki zarurat nahi |
key help karta hai React ko re-render optimize karne me | JS 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
yaprops
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:
Feature | Plain JavaScript | React |
Rendering | Manually (via DOM) | Automatically (via JSX + Virtual DOM) |
Re-rendering | Developer handles it manually | Handled 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 haireturn()
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
Term | Controlled Component | Uncontrolled Component |
Input Value | Controlled by React (via useState ) | Controlled by DOM |
Data Handling | Stored in component state | Accessed 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:
Line | Meaning |
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:
β 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:
e.target.name
= "email"
e.target
.value = "
john@gmail.com
"
π© 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:
name = "email"
value = "
john@gmail.com
"
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 withmap
, andkey
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 Concept | Used 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
2. Link Bootstrap in index.js
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. π
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! π