3

I am using React Native's <WebView> component.

The documentation has no mention of how to handle the keyboard hiding the webview when the webview's HTML contains an <input> which becomes focused on in Android.

Has anyone managed to solve this? I have found a library that seems to work for regular <View>, but not a <WebView>.

Naoto Ida
  • 1,275
  • 1
  • 14
  • 29

4 Answers4

10

you can wrap your WebView with a KeyboardAvoidingView

  <KeyboardAvoidingView
    behavior={Platform.select({ ios: "position", android: null })}
    enabled
    contentContainerStyle={{ flex: 1 }}
    keyboardVerticalOffset={Platform.select({ ios: offset, android: 20 })}
    style={{ flexGrow: 1 }}
  >
    <WebView/>
  </KeyboardAvoidingView>
Luis
  • 1,242
  • 11
  • 18
  • 1
    May I know what's the value of `offset`? I had to set it to `-50` on iOS in order to get my iPhone6 display the first input at the beggining of the view when it's focused... – Dimitri Kopriwa Jun 13 '20 at 10:57
3

Have you thought about responding to system level events for the keyboard appearing and disappearing, then adjusting the WebView size appropriately?

There is an old question about how to handle this, it may or may not still be relevant. This answer in particular shows how to handle keyboard events. https://stackoverflow.com/a/33585501/1403

DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
  if (!frames.endCoordinates) return;
  this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
  this.setState({keyboardSpace:0});
});

You could use the frames.endCoordinates.height value to alter the height of your WebView, ensuring that the content is not hidden behind the keyboard.

Community
  • 1
  • 1
AidenMontgomery
  • 1,612
  • 1
  • 17
  • 24
0

Just raising awareness that this can also be simply achieved by using react-native-keyboard-spacer if you are not in for intricate keyboard control.

import KeyboardSpacer from 'react-native-keyboard-spacer';

class DemoApp extends Component {
  render() {
    return (
      <View>
        <WebView ... />
        <KeyboardSpacer/>
      </View>
    );
  }
}
Hady
  • 2,597
  • 2
  • 29
  • 34
0

I used WebView.onTouchStart and ScrollView.scrollTo. This is work like charm for me.

import { useRef } from "react";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp
} from "react-native-responsive-screen";

const scrollRef = useRef();

const scrolldown = () => {
   scrollRef.current.scrollTo((wp("100%") * 2) / 3);
};

<ScrollView ref={scrollRef} >
...

<WebView onTouchStart={scrolldown} >
...
Mortadha Fadhlaoui
  • 388
  • 1
  • 5
  • 16