React Native: handle TextInput, Button events with state hook (2020)

February 17, 2020 Goodman Loading... Post a comment

This article will show you how to handle TextInput, Button events in React Native with state hook. You will also learn how to dismiss the device’s keyboard after the button is pressed.

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

export default function App() {
  // initize the state hook
  const [name, setName] = useState('');

  // Whenever the textinput value changes
  const txtHandler = enteredName => {
    setName(enteredName);
  }

  // when the OK button is pressed
  const btnHandler = () => {
    // do whatever you like with the name typed into the text field
    console.log(name);
    
    // dismiss the Keybaord
    Keyboard.dismiss();
  }

  return (
    <View style={styles.container}>
      <Text>Enter your name:</Text>
      <TextInput style={styles.input} placeholder="Enter your name" value={name} onChangeText={txtHandler} />
      <Button title="OK" onPress={btnHandler} />
    </View> 
  );
}

// styling
const styles = StyleSheet.create({
  container: {
    marginTop: 100,
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'flex-start'
  },
  input: {
    padding: 10,
    marginVertical: 20,
    width: 200,
    borderBottomColor: '#ddd',
    borderBottomWidth: 1
  }
});

I used Expo and tested the code on my iPad.

Try it yourself and have fun.

avatar

Related Articles