new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React · Learn · all subjects

rendering-patterns

154 notes in this subject, read out of this brain and free to use. This is page 3 of 3.

React components return single JSX element, use Fragments for multiple

React components must return a single JSX element. When you have multiple adjacent JSX elements, you must wrap them in a Fragment using the <> and </> syntax. Adjacent JSX elements without wrapping cause an error: 'Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX Fragment <>...</>?'

Example: Converting HTML to JSX

Example showing how to convert valid HTML to valid JSX: ```js export default function TodoList() { return ( <> <h1>Hedy Lamarr's Todos</h1> <img src="https://react.dev/images/docs/scientists/yXOvdOSs.jpg" alt="Hedy Lamarr" className="photo" /> <ul> <li>Invent new traffic lights</li> <li>Rehearse a movie scene</li> <li>Improve the spectrum technology</li> </ul> </> ); } ``` This demonstrates wrapping multiple elements in a Fragment (<>), closing self-closing tags (/>), closing all elements (</li>), and using className instead of class.

Exception: aria-* and data-* attributes keep dashes

For historical reasons, aria-* and data-* attributes are written as in HTML with dashes, not in camelCase.

JSX Rule 3: Use camelCase for attributes

In React, many HTML and SVG attributes are written in camelCase instead of kebab-case. For example, stroke-width becomes strokeWidth. Since class is a reserved word in JavaScript, use className instead in JSX, named after the corresponding DOM property.

JSX Rule 2: Close all tags

JSX requires tags to be explicitly closed. Self-closing tags like <img> must become <img />, and wrapping tags like <li>oranges must be written as <li>oranges</li>.

JSX Fragment syntax

Fragments are empty tags written as <> and </> that let you group elements without leaving any trace in the browser HTML tree. They are useful when you need a wrapper but don't want to add an extra DOM node.

Why multiple JSX tags must be wrapped

JSX is transformed into plain JavaScript objects under the hood. You cannot return two objects from a function without wrapping them into an array. This is why you also cannot return two JSX tags without wrapping them into another tag or a Fragment.

JSX Rule 1: Return a single root element

To return multiple elements from a component in JSX, wrap them with a single parent tag. You can use a regular tag like <div>, or use an empty Fragment written as <> and </> to group elements without leaving any trace in the browser HTML tree.

React components combine rendering logic and markup

In React, rendering logic and markup live together in the same place—components. Each React component is a JavaScript function that may contain some markup that React renders into the browser. This ensures that a component's rendering logic and markup stay in sync with each other on every edit.

JSX and React are separate

JSX and React are two separate things that are often used together, but can be used independently of each other. JSX is a syntax extension, while React is a JavaScript library.

JSX is a syntax extension for JavaScript

JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Most React developers prefer JSX for its conciseness, and most codebases use it.

React component is a JavaScript function

A React component is a JavaScript function that you can sprinkle with markup. React puts interactivity first while using the same technology as traditional web development.

Component names must start with capital letter

React component names must start with a capital letter or they won't work. This is how React distinguishes components from regular HTML tags. For example, <Profile /> starts with a capital P so React knows it refers to a component, while <section> is lowercase so React knows it refers to an HTML tag.

Components are reusable UI elements

React components are reusable UI elements for your app. They combine markup, CSS, and JavaScript into custom components that can be rendered on multiple pages and in multiple places.

JSX syntax for markup in JavaScript

React components use JSX syntax to embed markup inside JavaScript. JSX looks like HTML but is actually JavaScript under the hood. Components return JSX markup.

Return statement with multi-line markup requires parentheses

If your markup isn't all on the same line as the return keyword, you must wrap it in a pair of parentheses. Without parentheses, any code on the lines after return will be ignored due to JavaScript automatic semicolon insertion. The correct syntax is: return ( <div>...</div> );

Single-line return statement does not need parentheses

Return statements can be written all on one line without parentheses. For example: return <img src="..." alt="..." />;

Parent and child components

When a component renders other components, the outer component is called a parent component and the inner components are called child components. A component can be used as a child in multiple places and multiple times.

Never nest component definitions

Components can render other components, but you must never nest their definitions inside other components. Defining a component inside another component is very slow and causes bugs. Instead, define every component at the top level. When a child component needs data from a parent, pass it by props instead of nesting definitions.

Root component in React app

Your React application begins at a root component. Usually it is created automatically when you start a new project. For example, if you use CodeSandbox or the framework Next.js, the root component is defined in pages/index.js. Most React apps use components all the way down, meaning components are used not only for reusable pieces like buttons but also for larger pieces like sidebars, lists, and complete pages.

Example: Basic component definition and export

export default function Profile() { return ( <img src="https://react.dev/images/docs/scientists/MK3eW3Am.jpg" alt="Katherine Johnson" /> ) }

Example: Nesting components - Gallery with multiple Profile components

function Profile() { return ( <img src="https://react.dev/images/docs/scientists/MK3eW3As.jpg" alt="Katherine Johnson" /> ); } export default function Gallery() { return ( <section> <h1>Amazing scientists</h1> <Profile /> <Profile /> <Profile /> </section> ); }

Export component with export default

Use the export default prefix before the function definition to mark the main function in a file so that you can later import it from other files. The syntax is: export default function ComponentName() { }

Use filter() to display only specific components

Use JavaScript's filter() method to create a filtered array before mapping. filter() takes a test function that returns true or false, and returns a new array containing only items that passed the test. For example: const chemists = people.filter(person => person.profession === 'chemist');

Nested map() calls for nested lists

For rendering nested lists, use nested map() calls. Each map needs its own key. For example, rendering recipes with ingredients: {recipes.map(recipe => <div key={recipe.id}><h2>{recipe.name}</h2><ul>{recipe.ingredients.map(ingredient => <li key={ingredient}>{ingredient}</li>)}</ul></div>)}.

Rendering multiple DOM nodes per list item with key

When each item needs to render multiple DOM nodes, the short <></> Fragment syntax does not accept a key prop. Instead, either group them into a single <div>, or use the explicit <Fragment> syntax to pass a key: import { Fragment } from 'react'; const listItems = people.map(person => <Fragment key={person.id}><h1>{person.name}</h1><p>{person.bio}</p></Fragment>);. Fragments disappear from the DOM, producing a flat list of elements.

Rules for list keys

Keys must be unique among siblings (the items in the same array), but it is okay to use the same keys for JSX nodes in different arrays. Keys must not change between renders, or that defeats their purpose. Do not generate keys while rendering.

Keys are not passed as props to components

The key prop is only used as a hint by React itself; components do not receive key as a prop. If your component needs an ID, you have to pass it as a separate prop. For example: <Profile key={id} userId={id} />.

Why array index is a bad key

Using an item's index in the array as its key leads to subtle and confusing bugs. If the order in which items render changes over time (due to sorting, insertion, or deletion), the index as a key will cause items to lose their state and React will recreate components incorrectly. Instead, use a stable ID based on the data.

Every list item needs a unique key prop

JSX elements directly inside a map() call always need a key prop. Give each array item a key — a string or number that uniquely identifies it among siblings. For example: <li key={person.id}>. Keys tell React which array item each component corresponds to, so React can match them up later even if the array items move, get inserted, or get deleted.

Keys should come from stable data sources

Rather than generating keys on the fly, include them in your data. Good sources for keys: database IDs (which are unique by nature), or for locally generated data use an incrementing counter, crypto.randomUUID(), or a package like uuid when creating items. Do not use array index as key, and do not generate keys randomly with Math.random().

Arrow function implicit vs explicit return in map

Arrow functions implicitly return the expression right after =>, so no return statement is needed: const listItems = people.map(person => <li>{person}</li>). However, you must write return explicitly if the => is followed by a curly brace: const listItems = people.map(person => { return <li>{person}</li>; }). Arrow functions with => { are said to have a block body, and they require an explicit return statement.

Use map() to render lists from arrays

To render multiple similar components from array data, use JavaScript's map() method to transform the array into JSX nodes. Call map() on the array and return JSX for each item. For example: const listItems = people.map(person => <li>{person}</li>);

Extract list item components with key placement

When extracting a list item into its own component, place the key on the component element in the map, not on the root element inside the component. For example: {recipes.map(recipe => <Recipe {...recipe} key={recipe.id} />)} instead of placing key inside the Recipe component. This is because the key is needed in the context of the surrounding array.

Give your agent this brain