Ideal boilerplate for your reusable React component
Getting started with a functional React component is easy but when we are building reusable components we should keep somethings in mind.
- We can render custom markup inside the component to make it more flexible.
- We can add classes to the component for modifying the styling of the component.
- We can set attributes of the element the container is wrapping. (e.g. aria attributes, data attributes);
To ensure that our React component can support all of them we should use the following code as boilerplate.
First we destructure all the props we need in our component and then collect all the remaining props in props
variable.
Then we merge the className prop with our own component's classes.
At last, we assign the className and spread the other props and render children inside the div.
We can then use it like this
PRO TIP: in our component to avoid hardcoding the div element as wrapper, we can implement as
prop in the component like this.
then it will be used like this
Don't miss what's next. Subscribe to {In a Dev's shoes}: