Day 5: Lists, Keys & Styling
Day 5: Lists, Keys & Styling
Today is about making things look good and handling collections of data.
Rendering Lists
In React, we donât use for loops inside JSX. Instead, we use JavaScriptâs .map() array method.
const fruits = ['Apple', 'Banana', 'Cherry'];
function FruitList() {
return (
<ul>
{fruits.map((fruit) => (
<li>{fruit}</li>
))}
</ul>
);
}
The Importance of Keys
If you run the code above, check your console. Youâll see a warning:
Warning: Each child in a list should have a unique "key" prop.
Keys help React identify which items have changed, been added, or been removed. This is crucial for performance and bug prevention. A key should be a unique ID from your data.
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
];
function UserList() {
return (
<ul>
{users.map((user) => (
// Key goes on the outermost element inside map()
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Note: Avoid using the array index (index) as a key if the list implementation allows reordering or inserting/deleting items. It can cause subtle bugs.
Styling in React
There are many ways to style React apps.
1. Inline Styles
You can pass a JavaScript object to the style prop. Properties are camelCased.
<div style={{ color: 'red', backgroundColor: 'black' }}>
Error Message
</div>
Pros: Quick for dynamic values. Cons: messy, no pseudo-classes (:hover).
2. CSS Classes (Standard)
Just import a CSS file and use className.
/* App.css */
.btn {
background: blue;
color: white;
}
import './App.css';
<button className="btn">Click me</button>
3. CSS Modules
This is the preferred way for pure CSS in React. It scopes CSS to the component so class names donât clash.
Name your file Button.module.css.
/* Button.module.css */
.btn {
background: green;
}
import styles from './Button.module.css';
// React converts this to a unique class like "Button_btn__xyz123"
<button className={styles.btn}>Click me</button>
4. Utility Classes (Tailwind CSS)
If you set up your project with Tailwind (like this blog!), you use utility classes directly.
<button className="bg-blue-500 text-white px-4 py-2 rounded">
Click me
</button>
Homework for Day 5:
- Create an array of objects representing âMoviesâ. Each movie has
id,title, andyear. - Map over them and display them as cards.
- Use conditional styling: if the movie was released before 2000, display the year in red; otherwise, display it in green.
Halfway there! Day 6 is all about Forms.