react-nativereact-native-textinput

How to add red asterisk in react native TextInput placeholder?


Inside TextInput, I want to have a red asterisk after placeholder text which is grey in color.

<TextInput
      keyboardType="numeric"
      placeholder={t('Enter OTP')}
      placeholderTextColor="#C4C4C4"
      value={inputOTP}
      onChangeText={text => setInputOTP(text)}
      style={styles.textInput}
/>

I want a red asterisk next to P in EnterOTP. Is absolute position the only way to do it?


Solution

  • There is no direct method to do this.What I did is add text with asterix in front of the TextInput and show hide conditionally when there is value in TextInput or not,

        const [title, setTitle] = useState();
        const {
         control,
         handleSubmit,
         formState: {errors},
        } = useForm({});
    
        <View style={{flexDirection: 'row',}}>
              <Controller
                control={control}
                rules={{
                  required: true,
                }}
                render={({field: {onChange, onBlur, value}}) => (
                  <TextInput
                    autoFocus
                    onChangeText={(val) => {
                      onChange(val);
                      setTitle(val);
                    }}
                    value={value}
                    onBlur={onBlur}
                    placeholder={'Type activity name here'} >
                  </TextInput>
                )}
                name="activityName"
              />
              {title ? <Text></Text> : <Text style={{color: 'red',fontSize: 17,height: 13,}}>*</Text>}
            </View>
    

    The Controller here comes from react-hook-forms which is not related to this question.You can use TextInput without Controller also.