Sub topic 1
Embedding JavaScript Expressions in JSX
Prerequisites
This chapter assumes basic JavaScript arrays, objects, arrow functions, and map. You should also know React function components, props, JSX, and the useState hook.
Embedding JavaScript expressions in JSX
JSX is a syntax that lets React components describe user-interface elements. Inside JSX, curly braces embed a JavaScript expression. An expression produces a value, such as a variable, property access, function call, or conditional expression.
function Greeting({ name }) {
const message = `Hello, ${name}`;
return <h1>{message}</h1>;
}React evaluates message and places its result inside the h1. Curly braces are for JavaScript expressions, not complete statements such as if or for.
Turning arrays into elements with `map`
map creates a new array by transforming each item in an existing array. In JSX, use it to transform data objects into React elements.
const people = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
];
function PeopleList() {
return (
<ul>
{people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}The arrow function returns one li for each person. The resulting array becomes the children of ul.
Rendering your first list
React can render arrays of elements directly. Keep the data separate from the component markup when possible. This makes the transformation easier to read and allows the same data to support other views.
Why every list item needs a key
A key is a stable identifier React uses to match an element with its previous version during updates. Give each sibling list item a unique key from the data, usually a database or application ID.
Keys are used by React and are not passed to the component as a prop. Avoid array indexes when items can be inserted, removed, or reordered. An index can then refer to a different item, causing state or DOM updates to attach to the wrong row.
Exercise
Why is person.id a better key than the array index when people can be reordered?
Show answer
The ID stays attached to the same person, while the index changes when the order changes.