Sobes.tech
Middle

How to type components with HTML attributes and refs?

sobes.tech AI

Answer from AI

In TypeScript, for typing React components that accept HTML attributes and refs, the built-in types from @types/react are usually used.

For functional components with forwardRef, you can use React.ForwardRefRenderFunction or React.forwardRef with generics.

Example of typing a component with HTML attributes and a ref to an input element:

import React, { forwardRef, InputHTMLAttributes } from 'react';

interface MyInputProps extends InputHTMLAttributes<HTMLInputElement> {
  customProp?: string;
}

const MyInput = forwardRef<HTMLInputElement, MyInputProps>((props, ref) => {
  const { customProp, ...rest } = props;
  return <input ref={ref} {...rest} />;
});

export default MyInput;

Here:

  • InputHTMLAttributes<HTMLInputElement> adds all standard attributes for <input>.
  • forwardRef allows passing a ref to the DOM element.

For other elements, you can use the corresponding interfaces, such as ButtonHTMLAttributes<HTMLButtonElement>, etc.

This ensures correct typing of props and refs, improving autocomplete and preventing errors.

How to type components with HTML attributes and refs… - sobes.tech