sajad torkamani

Suppose you want to create a component that is a wrapper around an existing HTML element like the <button> element.

For example, you might want to create a <Toolbar> the component that acts exactly like a button but has specific classes applied depending on whether it’s in an active state or not.

Here’s an approach you can take (example):

import React, { ButtonHTMLAttributes } from 'react'
import classNames from 'classnames'

// First, you declare the component's props as the same as
// the native HTMLButtonElement, and add any extra props.
type Props = ButtonHTMLAttributes<HTMLButtonElement> & {
  isActive?: boolean
}

const ToolbarButton: React.FC<Props> = ({
  className,
  isActive = false,
  ...props
}) => {
  const defaultClasses = 'border px-2 py-1 border-black mr-3'

  return (
    <button
      // This is the essential step. You want to spread all the
      // props to the button.
      {...props}
      className={classNames(
        { 'bg-black text-white': isActive },
        defaultClasses,
        className
      )}
    />
  )
}

export default ToolbarButton