Naoto Ida
Naoto Ida

Reputation: 1295

Keyboard hides content for Android React Native webview

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>.

Upvotes: 4

Views: 14659

Answers (5)

Pablo
Pablo

Reputation: 1

I used KeyboardAvoidingView but added a container inside with the following styles:

<KeyboardAvoidingView
  behavior={Platform.OS == "ios" ? "padding" : "height"}
  style={{ flex: 1 }}
>
  <SafeAreaView style={styles.contenedorView}>
      <WebView
        ...

const styles = StyleSheet.create({
contenedorView: {
justifyContent: "flex-start",
position: "relative",
flex: 1,},

Upvotes: 0

Morta
Morta

Reputation: 399

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} >
...

Upvotes: 0

Luis
Luis

Reputation: 1500

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>

Upvotes: 10

Hady
Hady

Reputation: 2674

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>
    );
  }
}

Upvotes: 0

AidenMontgomery
AidenMontgomery

Reputation: 1612

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.

Upvotes: 3

Related Questions