Aquí tienes un componente de TextInput personalizado para React Native que maneja estados y estilos dinámicos:
import React, { useState } from 'react';
import { View, TextInput, Text, StyleSheet } from 'react-native';
const CustomTextInput = ({
label,
placeholder,
value,
onChangeText,
error,
errorMessage,
style,
inputStyle,
...props
}) => {
const [isFocused, setIsFocused] = useState(false);
const handleFocus = () => {
setIsFocused(true);
};
const handleBlur = () => {
setIsFocused(false);
};
const getInputStyle = () => {
if (error) {
return [styles.input, styles.inputError, inputStyle];
}
if (isFocused) {
return [styles.input, styles.inputFocused, inputStyle];
}
return [styles.input, inputStyle];
};
const getLabelStyle = () => {
if (error) {
return [styles.label, styles.labelError];
}
if (isFocused) {
return [styles.label, styles.labelFocused];
}
return styles.label;
};
return (
<View style={[styles.container, style]}>
{label && (
<Text style={getLabelStyle()}>
{label}
</Text>
)}
<TextInput
style={getInputStyle()}
placeholder={placeholder}
value={value}
onChangeText={onChangeText}
onFocus={handleFocus}
onBlur={handleBlur}
placeholderTextColor={error ? '#ff6b6b' : '#999'}
{...props}
/>
{error && errorMessage && (
<Text style={styles.errorText}>
{errorMessage}
</Text>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
marginVertical: 8,
},
label: {
fontSize: 14,
fontWeight: '500',
marginBottom: 6,
color: '#333',
},
labelFocused: {
color: '#007AFF',
},
labelError: {
color: '#ff6b6b',
},
input: {
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 10,
fontSize: 16,
backgroundColor: '#fff',
color: '#333',
},
inputFocused: {
borderColor: '#007AFF',
borderWidth: 2,
shadowColor: '#007AFF',
shadowOffset: {
width: 0,
height: 0,
},
shadowOpacity: 0.2,
shadowRadius: 4,
elevation: 2,
},
inputError: {
borderColor: '#ff6b6b',
borderWidth: 2,
backgroundColor: '#fff5f5',
},
errorText: {
color: '#ff6b6b',
fontSize: 12,
marginTop: 4,
fontWeight: '400',
},
});
export default CustomTextInput;
Y aquí un ejemplo de cómo usarlo:
import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import CustomTextInput from './CustomTextInput';
const ExampleScreen = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [emailError, setEmailError] = useState(false);
const [passwordError, setPasswordError] = useState(false);
const validateEmail = (text) => {
setEmail(text);
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
setEmailError(!emailRegex.test(text) && text.length > 0);
};
const validatePassword = (text) => {
setPassword(text);
setPasswordError(text.length < 6 && text.length > 0);
};
return (
<View style={styles.container}>
<CustomTextInput
label="Email"
placeholder="Ingresa tu email"
value={email}
onChangeText={validateEmail}
error={emailError}
errorMessage="Por favor ingresa un email válido"
keyboardType="email-address"
autoCapitalize="none"
/>
<CustomTextInput
label="Contraseña"
placeholder="Ingresa tu contraseña"
value={password}
onChangeText={validatePassword}
error={passwordError}
errorMessage="La contraseña debe tener al menos 6 caracteres"
secureTextEntry
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#f5f5f5',
},
});
export default ExampleScreen;
Características del componente:
- Estados dinámicos: Cambia estilos automáticamente en focus, error y estado normal
- Validación de errores: Muestra mensajes de error personalizados
- Estilos personalizables: Permite sobrescribir estilos mediante props
- Accesibilidad: Mantiene todas las props nativas de TextInput
- Label dinámico: El label cambia de color según el estado
Props disponibles:
label: Texto del label
error: Boolean para estado de error
errorMessage: Mensaje a mostrar en caso de error
style: Estilos del contenedor
inputStyle: Estilos específicos del input
- Todas las props nativas de TextInput
El componente es reutilizable y fácil de integrar en cualquier formulario de tu aplicación.