How to useRef in Hoc for html element using typescript

456 views Asked by At

This is my code

import React, { FC, InputHTMLAttributes, useEffect, useRef } from 'react';

type TElementType = HTMLInputElement | HTMLTextAreaElement;
type TElementWithAttributes = InputHTMLAttributes<HTMLInputElement>;

interface Props {
  submitTouched: boolean;
}

const withInput = (Comp: FC<TElementWithAttributes>): FC<Props> => props => {
  const { submitTouched } = props;

  const refValue: React.RefObject<TElementType> = useRef(null);

  const updateErrors = (val: string) => {
    // handle errors
  };

  useEffect(() => {
    if (submitTouched && refValue.current) {
      updateErrors(refValue.current.value);
    }
  }, [submitTouched]);

  const InputOrTextarea = (
    <>
      <Comp name="somename" type="text" value="somevalue" ref={refValue} />
    </>
  );
  return InputOrTextarea;
};

export default withInput;

I am getting error on ref={refValue}

Type '{ name: string; type: string; value: string; ref: RefObject; }' is not assignable to type 'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & TElementWithAttributes & { children?: ReactNode; }'.

1

There are 1 answers

0
Titian Cernicova-Dragomir On BEST ANSWER

ref is added to the html props by React.DetailedHTMLProps that is why you are getting an error. Try:

type TElementType = HTMLInputElement | HTMLTextAreaElement;
type TElementWithAttributes = React.DetailedHTMLProps<InputHTMLAttributes<TElementType>, TElementType>

Playground Link