import React, {forwardRef, useImperativeHandle, useRef, useState} from "react"; import {…
- User
import React, {forwardRef, useImperativeHandle, useRef, useState} from "react"; import { ColorValue, DimensionValue, Keyboard, KeyboardTypeOptions, ReturnKeyTypeOptions, StyleProp, TextInput, TouchableOpacity, View, ViewStyle, } from "react-native";
import Icon from "@components/icon";
import Images from "@config/Images"; import {iComponentProps} from "@config/types/CommonInterface"; import {ComponentIdType} from "@config/types/CommonTypes";
import {useThemeAwareObject} from "@styles/theming/ThemingHelper"; import Typography from "@styles/Typography"; import {hp, wp} from "@utils/ResponsiveScreenUtil";
import Styles from "./Styles";
type OnChangeTextType = (id: string | number | null, text: string) => void; interface iTextInputProps extends iComponentProps { /** Id of an element / id?: ComponentIdType; /* Width of input / width?: DimensionValue | undefined; /* height of input / height?: DimensionValue | undefined; /* border effect of input when in focus / onFocusBorderColor?: string; /* border effect of input when in blur / onBlurBorderColor?: string; /* background color of the input / backgroundColor?: string; /* border width of the input / borderWidth?: number; /* editable (default : true) / editable?: boolean; /* container style / containerStyle?: StyleProp; /* secure entry text (default : false) / isSecure?: boolean; /* placeholder text / placeholder: string; /* placeholder text color / placeholderTextColor?: string; /* textinput text color / textColor?: string; /* textinput font size / fontSize?: number; /* keyBoard Type (default: 'default') / keyBoardType?: KeyboardTypeOptions; /* Callback function when pressed / onChangeText: OnChangeTextType; / value of the input field / value?: string; / max characters allowed in the input / maxLength?: number; / On Submit Editing / onSubmitEditing?: () => void; / Return Key Type Options */ returnKey?: ReturnKeyTypeOptions; multiline?: boolean | undefined; autoCapitalize?: "none" | "sentences" | "words" | "characters" | undefined; }
interface iTextInputRef { focus: () => void; }
// eslint-disable-next-line react/display-name const Input = forwardRef<iTextInputRef, iTextInputProps>( ( { id = null, width = "100%", height = hp(40), onFocusBorderColor = undefined, onBlurBorderColor = undefined, backgroundColor = undefined, borderWidth = 1.2, editable = true, containerStyle, isSecure = false, placeholder = "...", placeholderTextColor = undefined, textColor = undefined, fontSize = Typography.fontSizes.FONT_SIZE_17, keyBoardType = "default", onChangeText, value = "", maxLength, onSubmitEditing, returnKey = "default", multiline = false, autoCapitalize = "none", }, ref, ) => { const styles = useThemeAwareObject(Styles.createStyles);
const [borderColor, setBorderColor] = useState< string | undefined | ColorValue >(onBlurBorderColor); const [isSecureEntry, setSecureEntry] = useState(isSecure); const reference = useRef<TextInput>(null); const onChange = (text: string) => { onChangeText(id, text); }; const onFocus = () => { setBorderColor( onFocusBorderColor || styles.themeVariables.onFocusBorderColor, ); }; const onBlur = () => { setBorderColor( onBlurBorderColor || styles.themeVariables.onBlurBorderColor, ); }; /* Forwarding ref to parent */ useImperativeHandle(ref, () => { return { focus: () => { Keyboard.dismiss(); setTimeout(() => { reference.current?.focus(); }, 100); }, }; }); const renderSecureIcon = () => { if (isSecure) { return ( <TouchableOpacity activeOpacity={1} key={`${isSecureEntry}`} style={styles.secureContainer} onPress={() => { return setSecureEntry(!isSecureEntry); }} > {!isSecureEntry ? ( <Icon Image={Images.svgIcons.passwordShow} disabled color={styles.themeVariables.showHideIconBgColor} /> ) : ( <Icon Image={Images.svgIcons.passwordHide} disabled color={styles.themeVariables.showHideIconBgColor} /> )} </TouchableOpacity> ); } return null; }; return ( <View style={[ styles.container, { height, width, borderColor: borderColor || styles.themeVariables.onBlurBorderColor, borderWidth, backgroundColor: backgroundColor || styles.themeVariables.backgroundColor, }, containerStyle, ]} > <TextInput ref={reference} multiline={multiline} autoCapitalize={autoCapitalize} style={[ styles.textInput, { width, color: textColor || styles.themeVariables.textColor, paddingRight: isSecure ? wp(50) : wp(10), fontSize, textAlignVertical: multiline ? "top" : "center", }, ]} onFocus={onFocus} keyboardType={keyBoardType} placeholder={placeholder} secureTextEntry={isSecureEntry} placeholderTextColor={ placeholderTextColor || styles.themeVariables.placeholderTextColor } onBlur={onBlur} editable={editable} onChangeText={onChange} value={value} maxLength={maxLength} onSubmitEditing={onSubmitEditing} returnKeyType={returnKey} /> {renderSecureIcon()} </View> ); },);
export default Input; export type {OnChangeTextType}; this is text input class now the issue is if i create two textinput fields one after another like this the email field keyboard type is also password and if i remove password input field it works fine so i want it to apply the isSceure thing only for one element how can i do this
- Assistant
The issue you're encountering likely stems from a combination of prop naming inconsistencies and the handling of the
idprop in your customInputcomponent. When you render multipleInputcomponents without unique identifiers, they may inadvertently share state or props, leading to unexpected behavior—such as thekeyboardTypebeing incorrectly applied to both fields.Here's a step-by-step guide to resolve the problem:
-
Correct the
keyboardTypeProp Naming:In React Native's
TextInput, the prop is namedkeyboardType(all lowercase except for "Type"). However, in your customInputcomponent, you've named itkeyBoardTypewith an uppercase "B". This discrepancy means that React Native'sTextInputdoesn't recognize the prop, potentially falling back to default behaviors or causing conflicts.Update Your
InputComponent Props:interface iTextInputProps extends iComponentProps<ViewStyle> { // ... other props /** Keyboard Type (default: 'default') */ keyboardType?: KeyboardTypeOptions; // Changed from keyBoardType to keyboardType // ... other props }Update the
InputComponent Usage:<TextInput // ... other props keyboardType={keyboardType} // Ensure this matches React Native's TextInput prop // ... other props />This ensures that the
keyboardTypeis correctly passed to the underlyingTextInput. -
Assign Unique
idProps to EachInput:Your
Inputcomponent uses anidto differentiate between different input fields when handling text changes. If multipleInputcomponents share the sameid(or default tonull), theonChangeTexthandler may not function correctly, leading to issues like shared state or incorrect behavior.Update Your Usage to Include Unique
idProps:import Input from './path-to-your-input-component'; // Ensure you're importing the correct component const YourComponent = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleChangeText = (id, text) => { if (id === 'email') { setEmail(text); } else if (id === 'password') { setPassword(text); } }; return ( <> <Input id="email" // Unique ID for email placeholder={translate(translationKeys.EmailPlaceholder)} keyboardType="email-address" value={email} onChangeText={handleChangeText} /> <Input id="password" // Unique ID for password containerStyle={styles.textInputContainer} placeholder={translate(translationKeys.PasswordPlaceholder)} isSecure value={password} onChangeText={handleChangeText} /> </> ); };Explanation:
-
Unique
idValues: Assigning uniqueidvalues like"email"and"password"ensures that theonChangeTexthandler can accurately identify which input field is being updated. -
Single
onChangeTextHandler: Using a single handler likehandleChangeTextstreamlines state management based on theidprovided.
-
-
Ensure You're Using the Custom
InputComponent:In your usage example, you used
<TextInput />directly. However, based on your provided component, you should use the custom<Input />component to leverage the additional functionalities (like secure text entry and custom styling).Update Your Imports and Usage Accordingly:
// Instead of importing TextInput from 'react-native', import your custom Input import Input from './path-to-your-input-component'; const YourComponent = () => { // ...state and handlers return ( <> <Input id="email" placeholder={translate(translationKeys.EmailPlaceholder)} keyboardType="email-address" value={email} onChangeText={handleChangeText} /> <Input id="password" containerStyle={styles.textInputContainer} placeholder={translate(translationKeys.PasswordPlaceholder)} isSecure value={password} onChangeText={handleChangeText} /> </> ); }; -
Review the
onChangeTextHandler in theInputComponent:Ensure that your
Inputcomponent correctly passes theidandtextto theonChangeTextcallback.In Your
InputComponent:const onChange = (text: string) => { onChangeText(id, text); };This setup requires that each
Inputhas a uniqueidso that the parent can determine which state to update. -
Verify the Secure Text Entry Functionality:
Since you want only the password field to have the secure text entry feature, ensure that:
- Only the password
Inputhas theisSecureprop set totrue. - The email
Inputeither doesn't receive theisSecureprop or has it explicitly set tofalse.
Example:
<Input id="email" placeholder={translate(translationKeys.EmailPlaceholder)} keyboardType="email-address" value={email} onChangeText={handleChangeText} isSecure={false} // Explicitly set or omit since default is false /> <Input id="password" containerStyle={styles.textInputContainer} placeholder={translate(translationKeys.PasswordPlaceholder)} isSecure={true} // Enable secure text entry value={password} onChangeText={handleChangeText} /> - Only the password
-
Final Component Structure:
After implementing the above changes, your components should look like this:
Custom
InputComponent:// ...imports interface iTextInputProps extends iComponentProps<ViewStyle> { id?: ComponentIdType; width?: DimensionValue | undefined; height?: DimensionValue | undefined; onFocusBorderColor?: string; onBlurBorderColor?: string; backgroundColor?: string; borderWidth?: number; editable?: boolean; containerStyle?: StyleProp<ViewStyle>; isSecure?: boolean; placeholder: string; placeholderTextColor?: string; textColor?: string; fontSize?: number; keyboardType?: KeyboardTypeOptions; // Corrected prop name onChangeText: OnChangeTextType; value?: string; maxLength?: number; onSubmitEditing?: () => void; returnKey?: ReturnKeyTypeOptions; multiline?: boolean | undefined; autoCapitalize?: "none" | "sentences" | "words" | "characters" | undefined; } // ...component code with keyboardType corrected export default Input; export type { OnChangeTextType };Usage in Parent Component:
import React, { useState } from "react"; import { View, StyleSheet } from "react-native"; import Input from "./path-to-your-input-component"; // Ensure correct path const YourComponent = () => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const handleChangeText = (id, text) => { if (id === "email") { setEmail(text); } else if (id === "password") { setPassword(text); } }; return ( <View style={styles.container}> <Input id="email" placeholder="Enter your email" keyboardType="email-address" value={email} onChangeText={handleChangeText} /> <Input id="password" placeholder="Enter your password" isSecure={true} value={password} onChangeText={handleChangeText} containerStyle={styles.passwordInput} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, passwordInput: { marginTop: 16, }, }); export default YourComponent; -
Additional Recommendations:
-
Prop Validation: Consider using TypeScript or PropTypes to enforce prop types and prevent similar issues in the future.
-
Default Props: Ensure that default values for props are set appropriately to avoid unintended behaviors when props are omitted.
-
Component Naming: To avoid confusion between React Native's
TextInputand your customInputcomponent, you might consider renaming your custom component to something more distinctive, likeCustomInputorStyledInput.
-
By implementing these changes, each
Inputcomponent will operate independently, ensuring that properties likekeyboardTypeandisSecureare applied only to their respective fields. This should resolve the issue of the email field being affected by the password field and ensure that each input behaves as expected. -