Sub topic 2
Returning Multiple Elements with Fragments
Assume you know JavaScript functions, destructuring, map, basic HTML, and ES module imports and exports.
Fragments
A component must return one JSX value. A fragment groups sibling elements without adding a wrapper element to the browser's DOM.
function Row({ label, value }) {
return (
<>
<dt>{label}</dt>
<dd>{value}</dd>
</>
);
}The short syntax <>...</> is equivalent to React.Fragment. Use a fragment when an extra div would change the document structure or styling.
What JSX Compiles To
JSX is syntax that a build tool transforms into JavaScript function calls. With the automatic JSX runtime, this source:
<h1 className="title">Hi</h1>can become:
import { jsx as _jsx } from 'react/jsx-runtime';
const element = _jsx('h1', {
className: 'title',
children: 'Hi'
});The result is a React element description. React later uses that description to update the DOM. JSX is therefore not an HTML string and is not parsed by the browser as HTML.
Props and Children
Props are the input object passed to a component. A component reads props but should not mutate them.
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
function App() {
return <Greeting name="Ada" />;
}Content nested between component tags becomes the children prop.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}Composition
Composition means building a larger interface by placing small components inside one another.
function App() {
return (
<Card title="Welcome">
<p>This paragraph is rendered inside the card.</p>
</Card>
);
}Card does not need to know whether its children are a paragraph, a form, or another component. This keeps components focused and reusable.
Exercise
Why would you use a fragment instead of a div around two sibling elements?
Show answer
Use a fragment when you need one JSX return value but do not want an extra element in the DOM.