How to name props for React components

There are only two hard things in Computer Science: cache invalidation and naming things.

— Phil Karlton

Today I am going to talk about one of the hard things in React.js — Naming props for your React components.

In general, prop names should share some common rules with naming variables. For example, use lower camel case (e.g. isActive) and keep the name short ( < 50 characters ). However, there are also some best practices that are specific to React component props.

Here are some of the tips I learned from my experience in working with React.

Follow prop types:

  1. Array – use plural nouns. e.g. items
  2. Number – use prefix num or postfix count, index etc that can imply a number. e.g. numItems, itemCount, itemIndex
  3. Bool – use prefix is, can, has
    • is: for visual/behavior variations. e.g. isVisible, isEnable, isActive
    • can: fore behavior variations or conditional visual variations. e.g. canToggle, canExpand, canHaveCancelButton
    • has: for toggling UI elements. e.g. hasCancelButton, hasHeader
  4. Object – use noun. e.g. item
  5. Node – use prefix node. containerNode
  6. Element – use prefix element. hoverElement

Named to descibe the component itself

Props should be named to describe the componet itself. Props describe what a component does, not why it does. A common mistake is to name props after the current user or the current environment. For example:

  • hasSubmitPermission describes the permission of the user, and the reason for variation, but not the component itself. A better name could be hasSubmitButton. i.e.
    <MyForm hasSubmitButton={user.canSubmit} />
  • isMobileScreen describes the browser window size, and the reason for variation, but not the component itself. A better name could be isCompactLayout. i.e.
    <MyForm isCompactLayout={browser.isMobileScreen} />

Another common mistake is to use a name describing children components instead of the component itself. This is more likely when the props are supposed to pass down to the children.

  • <MyList onItemClick={...} /> could be more appropriate than <MyList onClick={...} />
  • areCommentsLoading should be isLoadingComments
  • hasIcon describes the existence of a child component. If what you want is to make more room for the ‘icon’ instead of toggling an icon, consider using isSpacious instead. ‘hasIcon’ is the answer to why, not what.

Event handler props

  1. Use on prefix for prop names, e.g. onSelect, onClick
  2. Use handle prefix for handler functions, e.g. <MyComp onClick={this.handleClick} />
  3. Avoid using build-in event handler prop names for customer event. For example, use onSelect instead of onFocus or onClick if the native focus/click event is not of interest.