DEV Community

Jeon
Jeon

Posted on

Auto Resize multiline TextInput in React Native

§ If you are not updating a text value programatically:

function Layout() {
  const [height, setHeight] = useState(40);

  return (
    <TextInput multiline
      style={{ height }}
      onContentSizeChange={(event) => 
        setHeight(event.nativEvent.contentSize.height)
      }
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

§ If you are updating a text value programatically by using setState:

 function Layout() {
+  const ref = useRef<TextInput>(null);
+  const [text, setText] = useState<string>("");
   const [height, setHeight] = useState(40);

+  useEffefct(() => {
+    ref.current?.setNativeProps({ text });
+  }, [text]);

   return (
     <TextInput multiline
+      ref={ref}
       style={{ height }}
+      onChangeText={setText}
       onContentSizeChange={(event) => 
         setHeight(event.nativEvent.contentSize.height)
       }
     />
   );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay