iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🧩

Inheriting Default Props with ComponentPropsWithoutRef

に公開

I have researched the best practices for creating components when developing with Next.js (React) and TypeScript.

During this, I realized that the way I was defining component types was nonsensical. I've successfully implemented a major improvement to my components, so I'd like to share it!

Before Improvement

The component type definition I had been using until now.

import React from 'react'
import styles from './Button.module.scss'

interface Props {
  color?: 'primary' | 'secondary'
  disabled?: boolean
  onClick?: () => void
  style?: React.CSSProperties
  children?: React.ReactNode
}

export const Button = (props: Props) => {
  const { color, disabled, onClick, style, children } = props

  return (
    <button
      type='button'
      className={[
        styles.root,
        `${color ? styles[color] : styles.primary}`,
        `${disabled ? styles.disabled : ''}`
      ].join(' ')}
      style={style}
      onClick={onClick}
    >
      {children}
    </button>
  )
}

When composing a page, it becomes necessary to adjust the spacing between components.

The problem with the code above is that since components used in pages or layouts generally shouldn't have margins, you need to apply separate styles to provide spacing between them. To handle this, I was explicitly providing a style prop.

However, this means having to manually set up a style prop for every single component where it might be needed, which is extremely redundant.

After Improvement

import React from 'react'
import styles from './Button.module.scss'

interface Props extends React.ComponentPropsWithoutRef<'button'> {
  color?: 'primary' | 'secondary'
  disabled?: boolean
  onClick?: () => void
  children?: React.ReactNode
}

export const Button = ({ color, disabled, onClick, style, children, ...props }: Props) => {
  return (
    <button
      type='button'
      className={[
        styles.root,
        `${color ? styles[color] : styles.primary}`,
        `${disabled ? styles.disabled : ''}`
      ].join(' ')}
      onClick={onClick}
      {...props}
    >
      {children}
    </button>
  )
}

After the improvement, the style prop was removed, and by having the Props type extend ComponentPropsWithoutRef, all the default props of the <button> element can be inherited.

Reference Articles

Discussion