InnerRef is null after ComponentDidMount()

Viewed 30

I am trying to access textarea via ref because I need to adjust it's size according to the content. innerRef is null even after componentDidMount. Does anyone know how to access the textarea so I can access it's properties?

export interface TextAreaProps extends Omit<HTMLProps<HTMLTextAreaElement>, 'onChange' | 'ref'> {

  /** A reference object to attach to the textarea. */
  innerRef?: React.RefObject<any>;
}

export class TextAreaBase extends React.Component<TextAreaProps> {
  static displayName = 'TextArea';
  static defaultProps: TextAreaProps = {
    innerRef: React.createRef<HTMLTextAreaElement>()
  };

  constructor(props: TextAreaProps) {
    super(props);
  }

  componentDidMount(): void {
    console.log(this.props.innerRef); //logs out null
  }

  render() {
    const {
      innerRef,
      ...props
    } = this.props;

    return (
      <textarea
        ref={innerRef}
        {...props}
      />
    );
  }


export const TextArea = React.forwardRef<HTMLTextAreaElement, TextAreaProps>((props, ref) => (
  <TextAreaBase {...props} innerRef={ref as React.MutableRefObject<any>} />
));
1 Answers

If you want to resize Textarea Use autosize.min.js Its a Very Light weight Lib. (3kb Aprox). which will resize your Textarea based on typed Content and Reduce also if Less content.

Refer : Autosize

Related