Skip to main content
Saved

Pattern Components Beginner

Props and Attributes

If you pass data into a component through props, you can configure it from the outside and reuse the same component in many places.

Examples
React, Vue, Svelte and native web
Read
4 min

The problem

You might need Submit and Cancel buttons that look identical except for the label, but without props, you’d be stuck copying nearly identical component files and changing one word in each.

The pattern

Props let you pass data in from the outside instead of hardcoding it inside the component. A Button component can accept a label prop, so you can pass label="Submit" or label="Cancel" and only have one component to maintain instead of one for each label.

Problem

I’ve seen codebases with SubmitButton.tsx, CancelButton.tsx, DeleteButton.tsx, SaveButton.tsx, UpdateButton.tsx, ConfirmButton.tsx… you get the idea. They all do the same thing with different hardcoded text.

Testing gets harder too, because with everything hardcoded inside the component, you can’t render a disabled button or a red delete button in a test without writing yet another file for it.

Solution

Props can be any type, such as strings, numbers, objects, arrays, or functions. You can pass user data and click handlers, and the component renders based on what you pass. You can also give a component markup to render inside itself. In React, whatever you put between a component’s opening and closing tags arrives as a prop called children, and Vue and Svelte have their own versions of this, which Slot covers.

Props belong to the parent component, so data flows one way, from the parent down to the child, and the child treats its props as read-only. If a component needs data that it changes itself, such as whether a menu is open, that data is state, which Component State covers. When a prop needs to change, the child calls a function that the parent passed in, such as onClick, and the parent’s code handles the change.

With sensible defaults, the code that uses a component doesn’t have to specify every prop. A variant might default to “primary,” and disabled to false. A missing required prop should produce an error, and TypeScript makes that easy by flagging it at compile time.

Web components have two separate ways to receive data. HTML attributes are always strings, and JavaScript properties can be any type. You use attributes in HTML markup, and properties from JavaScript, so a web component usually takes its strings as attributes and its functions and objects as properties.

Example

This Button component handles different labels and variants, all through props. Each tab shows the component’s definition and then how it’s used.

Basic Props

function Button({ label, onClick, disabled = false, variant = 'primary', size = 'medium', icon = null }) {
  return (
    <button
      className={`btn btn-${variant} btn-${size}`}
      onClick={onClick}
      disabled={disabled}
    >
      {icon && <span className="btn-icon">{icon}</span>}
      {label}
    </button>
  );
}

<Button label="Submit" onClick={handleSubmit} />
<Button label="Cancel" onClick={handleCancel} variant="secondary" />
<Button label="Delete" onClick={handleDelete} variant="danger" disabled={loading} />

Props Spreading

When you write a wrapper component, you often can’t list every prop that its users will want to pass, such as id or data-testid. In the first line below, ...rest collects every prop the component didn’t name, and {...rest} then puts them all on the div.

function Card({ title, children, className, ...rest }) {
  return (
    <div className={`card ${className || ''}`} {...rest}>
      <h2>{title}</h2>
      <div className="card-content">{children}</div>
    </div>
  );
}

<Card title="User Profile" className="profile-card" data-testid="profile-card">
  <UserDetails />
</Card>

TypeScript Props

An interface documents which props a component takes and what type each one is. A ? after the name marks a prop as optional, and the union type on variant limits it to three values, so a missing label or a variant of "warning" is a compile error.

interface ButtonProps {
  label: string;
  onClick: () => void;
  disabled?: boolean;
  variant?: 'primary' | 'secondary' | 'danger';
}

function Button({ label, onClick, disabled = false, variant = 'primary' }: ButtonProps) {
  return (
    <button className={`btn btn-${variant}`} onClick={onClick} disabled={disabled}>
      {label}
    </button>
  );
}

Props with Children

Here the Card takes markup in two ways. children is whatever is between the <Card> tags, and footer is an ordinary prop whose value happens to be JSX, which is how a React component can have more than one place for its users to fill in.

function Card({ title, footer, children }) {
  return (
    <div className="card">
      {title && <div className="card-header"><h3>{title}</h3></div>}
      <div className="card-body">{children}</div>
      {footer && <div className="card-footer">{footer}</div>}
    </div>
  );
}

<Card title="User Profile" footer={<Button label="Save" />}>
  <UserForm />
</Card>

Benefits

  • One component can cover many uses, so the same Button works for “Submit” and “Cancel” with a different prop.
  • Testing gets easier, because you can pass mock data as props and check the output without internal state getting in the way.
  • You can reuse a component like Button across projects, because it doesn’t depend on any one app’s data.
  • Props work well with Storybook, because you can document every variant by passing a different combination of props.
  • TypeScript catches mistakes at compile time, so if you pass the wrong type to a prop, your editor flags it before the code runs.
  • The logic stays in one place, so when you fix a bug in the component, the fix applies everywhere it’s used.

Tradeoffs

  • As you add configuration options, a component can end up with twenty props, and at that point it gets hard to use.
  • Conditional logic piles up, because most new props add another if statement inside the component.
  • Passing data through five layers of components to get it to a deeply nested child, which is known as prop drilling, is tedious and easy to get wrong.
  • Default values can hide bugs, because if someone passes undefined and the component silently falls back to the default, you might not notice the problem in the code that passed it.
  • Boolean props can be awkward, because disabled={false} is harder to read than leaving the prop out.
  • Spreading props with {...rest} makes it hard to tell which props end up on the element, and without TypeScript, nothing checks them.
  • Web component attributes only support strings, so complex data needs JSON serialization or separate property setters.
  • Each optional prop you add increases the number of combinations you need to test, and a boolean prop doubles it.

Summary

With props, you can use one component in many places by configuring it, instead of duplicating it for each use. If you pass data and callbacks as props, your components don’t depend on where their data comes from. Sensible defaults mean the code that uses a component only sets the props it needs, and TypeScript types catch a wrong or missing prop before the code runs.

See also

Next in Components Pure Component Components that render the same output for the same inputs, with no side effects, so memoization works and tests are predictable.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.