Course contentsShow
← React Native
Lesson 180 of 1,5553. Core Primitive ComponentsFree lesson

Customizing Focus States on Inputs

Learners will provide visual cues to the user when input fields gain or lose focus.

In this lesson, you will learn how to provide visual feedback to users when they interact with your input fields by customizing their appearance based on focus states.

Why Visual Cues Matter

When a user taps an input field, it enters a "focused" state, meaning it is ready to receive keyboard input. In React Native, the default styling might not be enough to grab the user's attention. By leveraging component state, we can change the border color, background, or scale of an input to confirm that it is currently active.

Implementing Focus States

To manage this, we use the useState hook to track whether the input is focused or not, and then apply that state to the onFocus and onBlur props of the TextInput component.

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

const CustomInput = () => {
  const [isFocused, setIsFocused] = useState(false);

  return (
    <TextInput
      style={[
        styles.input,
        { borderColor: isFocused ? '#007AFF' : '#CCCCCC' }
      ]}
      onFocus={() => setIsFocused(true)}
      onBlur={() => setIsFocused(false)}
      placeholder="Type here..."
    />
  );
};

const styles = StyleSheet.create({
  input: {
    borderWidth: 2,
    padding: 10,
    borderRadius: 8,
  },
});

How it Works

  1. The State Variable: isFocused acts as a boolean flag. It starts as false because the input isn't focused when the screen first loads.
  2. onFocus: This callback fires the moment the user taps the field. We set isFocused to true, triggering a re-render.
  3. onBlur: This fires when the user taps away from the field or closes the keyboard. We set isFocused back to false, reverting the input to its default style.
  4. Conditional Styling: By passing an array of styles to the style prop, we can dynamically override the borderColor based on the value of isFocused.

This pattern ensures the user always knows exactly which field they are interacting with, creating a much more polished and intuitive interface.

Key Takeaway: Use the onFocus and onBlur props in tandem with component state to create dynamic visual feedback that signals an input is ready for user interaction.