Components, JSX, and props

19.3

A component is a reusable piece of UI. A function component returns JSX and receives one props object.

On this page

Compose components

Start a component name with a capital letter. JSX lets you write elements close to their display logic. Use braces for JavaScript expressions and close every tag. Parents pass props to children.

function ProductCard({ name, available }) {
  return (
    <article>
      <h2>{name}</h2>
      <p>{available ? "Available" : "Sold out"}</p>
    </article>
  );
}

export default function Catalog() {
  return <ProductCard name="Pen" available={true} />;
}

Mount a client-side app

In a project with JSX support, install matching react and react-dom versions. Put a div with id="root" in your HTML. In your entry file, use createRoot once to render the exported Catalog component.

import { createRoot } from "react-dom/client";
import Catalog from "./Catalog.jsx";

const container = document.getElementById("root");
createRoot(container).render(<Catalog />);

Use stable keys in lists

Use map to turn data into elements. Give each sibling a stable key from the data, such as an ID. Keys help React match items when rows move, appear, or disappear.

const products = [
  { id: 101, name: "Notebook" },
  { id: 102, name: "Pencil" },
];

export default function ProductList() {
  return (
    <ul>
      {products.map(product => <li key={product.id}>{product.name}</li>)}
    </ul>
  );
}

Official references