0

I am creating a temperature converter with 3 textinput fields, one for C, one for F and one for K. When I enter e.g. a value in the C field, it calculates the values for F and K. All fine so far. But when I then want to enter a value in the F field, or go back to the C field, the values are stuck to the last calculated values.

How can I make all fields edible again to enter a new value in any field?

Regards, Lars

export const ConversionInput = () => {
  const [valueC, setValueC] = useState();
  const [valueF, setValueF] = useState();
  const [valueK, setValueK] = useState();

  return (
    <View>
      <View style={styles.container}>
        <Text style={styles.text}>Celcius:</Text>
        <TextInput
          style={styles.input}
          keyboardType="numeric"
          // value={valueC}
          value={
            (valueF && `${((parseFloat(valueF) - 32) / 1.8).toFixed(2)}`) ||
            valueC
          }
          onChangeText={(valueC) => setValueC(valueC)}
        />
        <Text style={styles.symbol}>&deg;C</Text>
      </View>
      <View style={styles.container}>
        <Text style={styles.text}>Fahrenheit:</Text>
        <TextInput
          style={styles.input}
          keyboardType="numeric"
          value={
            (valueC && `${(parseFloat(valueC) * 1.8 + 32).toFixed(2)}`) ||
            valueF
          }
          onChangeText={(valueF) => setValueF(valueF)}
        />
        <Text style={styles.symbol}>&deg;F</Text>
      </View>
      <View style={styles.container}>
        <Text style={styles.text}>Kelvin:</Text>
        <TextInput
          style={styles.input}
          keyboardType="numeric"
          value={
            (valueC && `${(parseFloat(valueC) + 273.15).toFixed(2)}`) ||
            (valueF &&
              `${((parseFloat(valueF) + 459.67) * 0.555555).toFixed(2)}`) ||
            valueK
          }
          onChangeText={(valueK) => setValueK(valueK)}
        />
        <Text style={styles.symbol}> K</Text>
      </View>
    </View>
  );
};
  • You can add logic to clear other values when you switch between textinuts by using isFocused() method of textinput. https://reactnative.dev/docs/textinput#isfocused – Mantu Jun 15 '21 at 11:08
  • you are going wrong with the `value` part of `TextInput`. Keep `value =valueC` and calculate value of `valueC` on `onChangeText` of `valueF`. As state update your UI will be re-render. Still issue then let me know? – Shahanshah Alam Jun 15 '21 at 12:03
  • That worked. Thanks a lot. I didn't need the isfocused. – Lars Cichowski Jun 17 '21 at 09:18

1 Answers1

0

You can clear the value of text field with the help of onFocus()

Mandeep Kaur
  • 114
  • 6