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
- The State Variable:
isFocusedacts as a boolean flag. It starts asfalsebecause the input isn't focused when the screen first loads. onFocus: This callback fires the moment the user taps the field. We setisFocusedtotrue, triggering a re-render.onBlur: This fires when the user taps away from the field or closes the keyboard. We setisFocusedback tofalse, reverting the input to its default style.- Conditional Styling: By passing an array of styles to the
styleprop, we can dynamically override theborderColorbased on the value ofisFocused.
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.