Home > Enterprise >  Changing text color clears TextInput in react-native
Changing text color clears TextInput in react-native

Time:01-31

I have tried getting the result in a couple of different ways but i don't know if this is a bug or if i am doing something wrong.

When changing the color in styling of my TextInput the input gets cleared and all text goes away showing only placeholder text.

const [focusInputTextColor, setFocusInputTextColor] = useState("000000");

const onFocusInput = () => {
    setFocusInputTextColor('#ffffff');
};

const onBlurInput = () => {
    setFocusInputTextColor('#000000');
};

<TextInput
    style={[styles.input,{color:focusInputTextColor}]}
    onChangeText={() => console.log("test")}
    placeholder="Placeholder here"
    placeholderTextColor="#000000"
    onFocus={() => onFocusInput()}
    onBlur={() => onBlurInput()}
/>

Am i doing something wrong or is this a bug?

CodePudding user response:

This behavior is likely due to the way you're handling the onChangeText event. The onChangeText event is called every time the text in the TextInput changes, but you're not updating the state with the new text. To fix this issue, try updating the state with the new text in the onChangeText event.


Edit - Q1: It could be because the onBlur event is being triggered before the onChangeText event. You can try updating the state with the input text in the onBlur event to see if that fixes the issue.

Here is an example:

const [inputText, setInputText] = useState("");
const [focusInputTextColor, setFocusInputTextColor] = useState("000000");

const onFocusInput = () => {
setFocusInputTextColor('#ffffff');
};

const onBlurInput = () => {
setFocusInputTextColor('#000000');
setInputText(inputText);
};

<TextInput
style={[styles.input,{color:focusInputTextColor}]}
onChangeText={text => setInputText(text)}
value={inputText}
placeholder="Placeholder here"
placeholderTextColor="#000000"
onFocus={() => onFocusInput()}
onBlur={() => onBlurInput()}
/>
  • Related