|
| 1 | +import React, {type BaseSyntheticEvent, useCallback} from 'react'; |
| 2 | +import {TextInput as RNTextInput, type TextInputChangeEventData, type TextInputProps, type LayoutChangeEvent} from 'react-native'; |
| 3 | + |
| 4 | +const adjustInputHeight = (element: BaseSyntheticEvent<TextInputProps, TextInputProps>['target']) => { |
| 5 | + element.style.height = 0; |
| 6 | + const newHeight = element.offsetHeight - element.clientHeight + element.scrollHeight; |
| 7 | + element.style.height = `${newHeight}px`; |
| 8 | +}; |
| 9 | + |
| 10 | +// we need this wrapper of TextInput on web because of multiline bug in react-native-web |
| 11 | +// https://github.com/necolas/react-native-web/issues/795 |
| 12 | +export const TextInput = (props: TextInputProps) => { |
| 13 | + const {multiline, onChange, onLayout, ...other} = props; |
| 14 | + |
| 15 | + const _onLayout = useCallback((event: LayoutChangeEvent) => { |
| 16 | + const element = event?.target; |
| 17 | + |
| 18 | + if (element && multiline) { |
| 19 | + adjustInputHeight(element); |
| 20 | + } |
| 21 | + |
| 22 | + onLayout?.(event); |
| 23 | + }, [multiline, onLayout]); |
| 24 | + |
| 25 | + const _onChange = useCallback((event: BaseSyntheticEvent<TextInputChangeEventData>) => { |
| 26 | + const element = event?.target || event?.nativeEvent?.target; |
| 27 | + |
| 28 | + if (element && multiline) { |
| 29 | + adjustInputHeight(element); |
| 30 | + } |
| 31 | + |
| 32 | + onChange?.(event); |
| 33 | + }, [multiline, onChange]); |
| 34 | + |
| 35 | + return ( |
| 36 | + <RNTextInput |
| 37 | + {...other} |
| 38 | + multiline={multiline} |
| 39 | + onChange={_onChange} |
| 40 | + onLayout={_onLayout} |
| 41 | + /> |
| 42 | + ); |
| 43 | +}; |
0 commit comments