Avoiding the Keyoard from Hiding the User Interface in React Native

Tiempo de lectura: 2 minutos

The KeyboardAvoidingView is a component in React Native that helps manage keyboard behavior on mobile devices, especially on small screens. When a text field or input is selected and the keyboard appears, The KeyboardAvoidingView adjusts the position of components on the screen to prevent them from being covered by the keyboard.

You should use KeyboardAvoidingView when you have text fields or forms in your app and you want to ensure that the keyboard does not hide any important content, such as send buttons or lists.

You don’t need to install anything extra to use KeyboardAvoidingView, since it is part of React Native from the start. You just need to import and configure the component correctly.

First, you need to import KeyboardAvoidingView from React Native:

import { KeyboardAvoidingView, Platform, View, Text, TextInput, StyleSheet, Button } from 'react-native';

You have a basic example of how to use KeyboardAvoidingView:

import React, { useState } from 'react';
import { KeyboardAvoidingView, Platform, TextInput, Button, StyleSheet, Text, View } from 'react-native';

const App: React.FC = () => {
  const [text, setText] = useState('');

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'} // Ajuste según la plataforma
    >
      <View style={styles.innerContainer}>
        <Text style={styles.header}>Bienvenido</Text>
        <TextInput
          style={styles.input}
          placeholder="Escribe algo aquí"
          value={text}
          onChangeText={setText}
        />
        <Button title="Enviar" onPress={() => alert(`Texto enviado: ${text}`)} />
      </View>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center', // Centra el contenido
    alignItems: 'center',     // Centra el contenido
  },
  innerContainer: {
    width: '80%',
    alignItems: 'center',     // Centra el contenido dentro del contenedor
  },
  header: {
    fontSize: 24,
    marginBottom: 20,
  },
  input: {
    width: '100%',
    height: 50,
    borderColor: '#ccc',
    borderWidth: 1,
    marginBottom: 20,
    paddingLeft: 10,
    borderRadius: 5,
  },
});

export default App;

In this case, we added more content and see how KeyboardAvoidingView helps adjust the entire design.

KeyboardAvoidingView is a very useful tool in React Native that adjusts the user interface to ensure that the content is not covered by the keyboard. It’s ideal for forms, text fields or any component that can be affected by the keyboard on a small screen.

Leave a Comment