Skip to content

Latest version doesn't handle empty refs if unmounted or not yet attached #411

@weedgrease

Description

@weedgrease

The latest version of this library contained this addition:

    useFormResetListener(libRef, () => {
      if (!isControlled) {
        const node = libRef.current!;
        const currentValue = node.value;
        requestAnimationFrame(() => {
          if (currentValue !== node.value) {
            resizeTextarea();
          }
        });
      }
    });

This is currently causing issues and throwing errors like

    TypeError: The provided value is not of type 'Element'.

      at Object.exports.convert (node_modules/jsdom/lib/jsdom/living/generated/Element.js:26:9)
      at Window.getComputedStyle (node_modules/jsdom/lib/jsdom/browser/Window.js:787:19)
      at getSizingData (node_modules/react-textarea-autosize/dist/react-textarea-autosize.browser.cjs.js:127:22)
      at resizeTextarea (node_modules/react-textarea-autosize/dist/react-textarea-autosize.browser.cjs.js:201:109)
      at node_modules/react-textarea-autosize/dist/react-textarea-autosize.browser.cjs.js:231:13
      at invokeTheCallbackFunction (node_modules/jsdom/lib/jsdom/living/generated/Function.js:19:26)
      at runAnimationFrameCallbacks (node_modules/jsdom/lib/jsdom/browser/Window.js:603:13)
      at Timeout.<anonymous> (node_modules/jsdom/lib/jsdom/browser/Window.js:581:11)

There are times, especially in testing frameworks where the the current value of the libRef is null.

Proposed changes:

export const useFormResetListener = (
  libRef: React.MutableRefObject<HTMLTextAreaElement | null>,
  listener: (event: Event) => any,
) => {
  useListener(document.body, 'reset', (ev) => {
    if (libRef.current?.form === ev.target) {
      listener(ev);
    }
  });
};

and

  if (isBrowser) {
    React.useLayoutEffect(resizeTextarea);
    useFormResetListener(libRef, () => {
      const node = libRef.current;
      if (!isControlled && node) {
        const currentValue = node.value;
        requestAnimationFrame(() => {
          if (currentValue !== node.value) {
            resizeTextarea();
          }
        });
      }
    });
    useWindowResizeListener(resizeTextarea);
    useFontsLoadedListener(resizeTextarea);
    return <textarea {...props} onChange={handleChange} ref={ref} />;
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions