Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.2Splitting an interface into components

Components let an interface be understood in pieces. Start with a working component, then extract a part when it has its own meaning, is repeated or makes the parent difficult to read.

Extract a component

JSX
function Header() {
  return (
    <header className="page-header">
      <h1 className="page-header__title">My tasks</h1>
    </header>
  );
}

export default function App() {
  return (
    <main className="task-page">
      <Header />
      <p className="task-page__summary">Plan the week</p>
    </main>
  );
}

A component may live in the same file while it is small. Move it to its own module when it grows or is used elsewhere. Export the component from that file and import it where needed.

Choose boundaries

Do not turn every element into a component. Good boundaries follow concepts in the interface: TaskList, TaskItem and TaskForm. Names such as BlueBox often describe appearance rather than purpose and are less useful.

The rendering tree

When App returns <Header />, React calls Header and places its returned header there. The browser does not receive a custom Header HTML element; it receives the standard HTML produced by the component.

Components render other components, forming a tree. Data normally travels down through props, while event handlers let children report actions to an owner higher in the tree.

Challenge: split the task page

Start with one App containing a heading, summary, list and add button. Extract Header, TaskList and AddTaskButton. Move TaskList to TaskList.jsx and import it.

Success criteria
  • The page looks unchanged.
  • Every component starts with a capital letter.
  • TaskList.jsx exports its component.
  • App.jsx imports it using the correct path.
Feedback 👍
Comments are sent via email to me.