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:
- Array – use plural nouns. e.g.
items
- Number – use prefix
num
or postfixcount
,index
etc that can imply a number. e.g.numItems
,itemCount
,itemIndex
- 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
- Object – use noun. e.g.
item
- Node – use prefix
node
.containerNode
- 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 behasSubmitButton
. 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 beisCompactLayout
. 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 beisLoadingComments
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 usingisSpacious
instead. ‘hasIcon’ is the answer to why, not what.
Event handler props
- Use
on
prefix for prop names, e.g.onSelect
,onClick
- Use
handle
prefix for handler functions, e.g.<MyComp onClick={this.handleClick} />
- Avoid using build-in event handler prop names for customer event. For example, use
onSelect
instead ofonFocus
oronClick
if the native focus/click event is not of interest.