{In a Dev's shoes} logo

{In a Dev's shoes}

Subscribe
Archives
January 10, 2019

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.

  1. We can render custom markup inside the component to make it more flexible.
  2. We can add classes to the component for modifying the styling of the component.
  3. 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.

Implementation

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

Usage

PRO TIP: in our component to avoid hardcoding the div element as wrapper, we can implement as prop in the component like this.

Implementation

then it will be used like this

Usage

Don't miss what's next. Subscribe to {In a Dev's shoes}:
Powered by Buttondown, the easiest way to start and grow your newsletter.