How to create ref inside react hoc using typescript without forwardedRef

174 views Asked by At

This is my code:

import React, {
  InputHTMLAttributes,
  Component,
  ComponentClass,
  TextareaHTMLAttributes
} from 'react';


// type TElementType = HTMLInputElement | HTMLTextAreaElement;
// type TAttributesType =
//   | InputHTMLAttributes<HTMLInputElement>
//   | TextareaHTMLAttributes<HTMLTextAreaElement>;

interface IClassType {
  somevalue: string;
}

type TElementType = HTMLInputElement;
type TAttributesType = InputHTMLAttributes<HTMLInputElement>;

const withInput = (Comp: ComponentClass<TAttributesType>): ComponentClass<IClassType> => {
  class MyInput extends Component<IClassType> {
    private refValue = React.createRef<TElementType>();

    componentDidMount() {
      console.log('do something');
    }

    render() {
      return (
        <>
          <Comp
            name="someinput"
            value="somevalue"
            type="text"
            ref={ref => {
              this.refValue = ref;
            }}
          />
        </>
      );
    }
  }

  return MyInput;
};

export default withInput;

This is the error on this.refValue = ref:

Type 'Component<TAttributesType, any, any> | null' is not assignable to type 'RefObject'. Type 'null' is not assignable to type 'RefObject'.

I have looked online and can only find examples of forwardedRefs. I do not need to forward a ref from my passed component, since the ref is only necessary within my hoc.

0

There are 0 answers