Skip to content

REACT Best Practices Props

Patrick Alvin Luwum edited this page Jun 20, 2018 · 1 revision

Props

Props provide configuration values for your component.

  1. Always use camelCase for prop names. Props can also be seen as attributes, and the convention set by React is to use camelCase for JSX attributes. Which makes it a good practice to always use camelCase for props.

image

  1. Omit the value of the prop when it is explicitly true.Even if we don’t assign true value to a prop, It’s considered as a true value, so there’s no need to assign ‘true’ as a value to the prop.

image

  1. Avoid using an array index as key prop, instead use an unique ID: DO NOT USE THE INDEX OF AN ITEM AS ITS KEY WHEN RENDERING A LIST. Don't do this:

image

The key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something from the middle? If the key is the same as before, React assumes that the DOM element represents the same set of components as before. Which is not the case, this is why it is advised to USE A UNIQUE ID. Each item should have a permanent and unique property. Ideally, a unique id should be assigned to each item at the time of creation. So it’s written out something like this:

image

  1. Always define explicit defaultProps for all non-required props. Providing defaultProps means the reader of your code doesn’t have to assume things, because they’ll know the default value for the prop just by looking at defaultProps while rendering components

image