Search code examples
reactjsreact-typescript

what is React.ComponentPropsWithoutRef for react typescript


For using React with typescript, what is React.ComponentPropsWithoutRef used for. Is there any documentation for this property?


Solution

  • The ComponentPropsWithoutRef type can be used to grab all the native attributes of an HTML element as the props type of your component.

    You can simply create a type that has all the native button attributes as props like this:

    type ButtonProps = React.ComponentPropsWithoutRef<"button">
    const Button = ({ children, onClick, type }: ButtonProps) => {
      return (
        <button onClick={onClick} type={type}>
          {children}
        </button>
      )
    }
    

    Here a link that talks about usage of ComponentPropsWithoutRef in typescript more. Refer "How to type (extend) HTML elements" and "ComponentPropsWithoutRef vs [Element]HTMLAttributes" sections