11import React from "react" ;
2- import {
3- AvoidSoftInput ,
4- AvoidSoftInputView ,
2+ import { View } from "react-native" ;
3+ import type {
4+ AvoidSoftInput as AvoidSoftInputType ,
5+ AvoidSoftInputView as AvoidSoftInputViewType ,
56 AvoidSoftInputViewProps ,
67} from "react-native-avoid-softinput" ;
78
9+ // `react-native-avoid-softinput` is an optional dependency and there is a possibility that it is not installed resulting in undefined references
10+ let AvoidSoftInput : typeof AvoidSoftInputType | null = null ;
11+ let AvoidSoftInputView : typeof AvoidSoftInputViewType | null = null ;
12+
13+ try {
14+ const avoidSoftInputPackage = require ( "react-native-avoid-softinput" ) ;
15+ AvoidSoftInput = avoidSoftInputPackage . AvoidSoftInput ;
16+ AvoidSoftInputView = avoidSoftInputPackage . AvoidSoftInputView ;
17+ } catch ( _ ) {
18+ console . warn (
19+ "AvoidKeyboardView: `react-native-avoid-softinput` is not installed, falling back to `View`. No keyboard avoiding capabilties will be used."
20+ ) ;
21+ }
22+
823/**
924 * Requires additional setup: https://mateusz1913.github.io/react-native-avoid-softinput/docs/guides
1025 * Cannot be used with Expo Go
@@ -26,19 +41,27 @@ const AvoidKeyboardView: React.FC<AvoidKeyboardViewProps> = ({
2641 ...rest
2742} ) => {
2843 React . useEffect ( ( ) => {
29- AvoidSoftInput . setShouldMimicIOSBehavior ( true ) ;
44+ if ( AvoidSoftInput ) {
45+ AvoidSoftInput . setShouldMimicIOSBehavior ( true ) ;
46+ }
3047 return ( ) => {
31- AvoidSoftInput . setShouldMimicIOSBehavior ( false ) ;
48+ if ( AvoidSoftInput ) {
49+ AvoidSoftInput . setShouldMimicIOSBehavior ( false ) ;
50+ }
3251 } ;
3352 } , [ ] ) ;
3453
35- return (
36- < AvoidSoftInputView
37- onSoftInputHidden = { onKeyboardHidden }
38- onSoftInputShown = { onKeyboardShown }
39- { ...rest }
40- />
41- ) ;
54+ if ( AvoidSoftInputView ) {
55+ return (
56+ < AvoidSoftInputView
57+ onSoftInputHidden = { onKeyboardHidden }
58+ onSoftInputShown = { onKeyboardShown }
59+ { ...rest }
60+ />
61+ ) ;
62+ } else {
63+ return < View { ...rest } /> ;
64+ }
4265} ;
4366
4467export default AvoidKeyboardView ;
0 commit comments