0

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.

Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63
  • 1
    I don't think this will resolve your issue (I'm not very familiar with typescript), but it appears you are mixing current and legacy ref syntax. With the current refs generated from `React.createRef` you simply attach the ref, i.e. `ref={this. refValue}`, to the component. – Drew Reese Oct 13 '20 at 07:27
  • The typescript error is basically saying that you are mixing up the current value of the ref with the ref itself. You would want to set this.refValue.current. But @Drew is right that the other syntax is easier. – Linda Paiste Oct 13 '20 at 07:48

0 Answers0