Components and props

A function that returns markup, and the values you hand it.

A React component is a function that returns markup.

function Greeting() {
  return <h1>Hello</h1>;
}

That markup is JSX: it looks like HTML and compiles to function calls. It is not a string — className instead of class, {} to drop a value in.

A component takes props: the values whoever uses it passes in.

function Greeting({ name }: { name: string }) {
  return <h1>Hello, {name}</h1>;
}

<Greeting name="Mai" />

The playground here is TypeScript, so the prop types are real: change name="Mai" to name={5} and the editor underlines it before you run anything.

Two rules that catch everyone

  • A component's name starts with a capital letter. <greeting /> is an HTML tag; <Greeting /> is your component.
  • It returns one element. Wrap siblings in <>…</> when you need two.

Try it

  1. Add a role prop and show it under the name.
  2. Render <Greeting /> three times with different names.
  3. Make role optional — role?: string — and see what the editor then insists you handle.
Loading...