A Few Pointers on React Component Props
Becca Bailey
Posted on September 12, 2019
One of the first things we learn as React developers are how to use props to pass arguments into our components. However, there are a few common pitfalls that we often run into when designing the API of our components that make our components more difficult to use and test. Here are a few pointers that will help us to write more usable components.
Think about the API of your React components the same way you would think about the API of a shared library. How can you make it as easy as possible for another user (or yourself) to get it right?
Required Props
Your components should have as few required props as possible. For example, boolean props shouldn't be required and should default to false. We see this pattern in the HTML spec and should mimic it in our components.
<MyButton disabled={false}/>
<MyButton disabled={true}/>
// vs
<MyButton />
<MyButton disabled />
Also, we should provide reasonable defaults for any props that don't affect the behavior of the component.
const MyButton = ({ color: color.primary }) => {
...
}
Data Structures
Sometimes, I see prop types that look like this.
// JS
MyComponent.propTypes = {
data: PropTypes.object.isRequired
}
If I am using this component, there's no way I can tell at a glance what the structure of this prop is. I would need to read through the logic in the render
method, and then hope for the best.
You could give data
a more specific type, like this.
MyComponent.propTypes = {
data: PropTypes.shape({
value: PropTypes.string,
id: PropTypes.number,
}).isRequired,
}
But an even better approach might be to flatten out this data structure.
MyComponent.propTypes = {
value: PropTypes.string,
id: PropTypes.number,
}
If you are dealing with formatted API data, it is okay to re-format this data at the top level for the sake of readability in your lower-level presentational components.
If you keep props as simple and readable as possible, I promise you will thank yourself later.
Posted on September 12, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.