TextInput Blur Event Handling in React Native

Handling focus and blur events is crucial for enhancing user experience in any application. React Native’s TextInput component offers built-in methods to accomplish this. This blog post will discuss how to handle the blur event in TextInput and give you practical examples to integrate into your apps.

Prerequisites

  • A functional React Native development environment
  • Basic understanding of React Native and JavaScript

A Simple TextInput Example

Let’s start by looking at a basic example of a TextInput component in React Native.

import React from 'react';
import { View, TextInput } from 'react-native';

const App = () => {
  return (
    <View>
      <TextInput placeholder="Focus me!" />
    </View>
  );
};

Handle Blur with onBlur

You can utilize the onBlur event to execute some code when the TextInput loses focus.

<TextInput
  placeholder="Focus me!"
  onBlur={() => {
    console.log('Input field has been blurred');
  }}
/>

The onBlur prop lets you run a function when the TextInput is no longer focused.

Real-world Example: Form Validation

Let’s say you’re building a form that needs validation when the user moves away from a TextInput. Here’s how you can do it:

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

const App = () => {
  const [email, setEmail] = useState('');
  const [error, setError] = useState('');

  const handleBlur = () => {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (!emailRegex.test(email)) {
      setError('Invalid email address');
    } else {
      setError('');
    }
  };

  return (
    <View>
      <TextInput
        placeholder="Enter your email"
        value={email}
        onChangeText={setEmail}
        onBlur={handleBlur}
      />
      {error ? <Text>{error}</Text> : null}
    </View>
  );
};

export default App;

Explanation

  • The handleBlur function runs when the input is blurred.
  • It validates the email and sets an error message if the email is invalid.

Use useRef to Control Focus

If you need to manually focus or blur a TextInput, you can use React’s useRef hook.

import React, { useRef } from 'react';
import { View, TextInput, Button } from 'react-native';

const App = () => {
  const inputRef = useRef(null);

  return (
    <View>
      <TextInput ref={inputRef} placeholder="I can be focused!" />
      <Button
        title="Blur Input"
        onPress={() => {
          inputRef.current.blur();
        }}
      />
    </View>
  );
};

Explanation

  • The useRef hook lets you reference a DOM node.
  • The blur method allows you to programmatically blur the TextInput.

Understanding the blur event in React Native’s TextInput is crucial for enhancing your app’s UX. You can easily validate forms, control focus, and execute other logic when an input field is blurred.

Similar Posts

Leave a Reply