DEV Community

Aditya Agarwal
Aditya Agarwal

Posted on

Ideal boilerplate for reusable React components

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.

import React from 'react';

function ReusableComp({ className, children, ...props }) {
  const classList = ['componentClass1', 'componentClass2', className];

  const classNames = classList.join(' ');
  return <div className={classNames} {...props}>{children}</div>
}

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

<ReusableComp className='special-item' title='actions'>
  <div>
    <button>Do Something</button>
    <a href="/go-somewhere">Go</a>
  </div>
</ReusableComp>

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

import React from 'react';

function ReusableComp({ className, children, as: Element, ...props }) {
  const classList = ['componentClass1', 'componentClass2', className];

  const classNames = classList.join(' ');
  return <Element className={classNames} {...props}>{children}</Element>
}

then it will be used like this

<ReusableComp as='section' className='special-item' title='actions'>
  <div>
    <button>Do Something</button>
    <a href="/go-somewhere">Go</a>
  </div>
</ReusableComp>

Latest comments (0)