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)