import React, { useState } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';
function toCelsius(fahrenheit) {
return ((fahrenheit - 32) * 5) / 9;
}
function toFahrenheit(celsius) {
return (celsius * 9) / 5 + 32;
}
function tryConvert(temperature, convert) {
const input = parseFloat(temperature);
if (Number.isNaN(input)) {
return '';
}
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
}
export default function TemperatureConverter() {
const [temperature, setTemperature] = useState('');
const [scale, setScale] = useState('c');
const handleCelsiusChange = (text) => {
setTemperature(text);
setScale('c');
};
const handleFahrenheitChange = (text) => {
setTemperature(text);
setScale('f');
};
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
return (
<View style={styles.container}>
<Text style={styles.label}>Celsius:</Text>
<TextInput
style={styles.input}
keyboardType="numeric"
value={celsius}
onChangeText={handleCelsiusChange}
accessibilityLabel="Celsius input"
/>
<Text style={styles.label}>Fahrenheit:</Text>
<TextInput
style={styles.input}
keyboardType="numeric"
value={fahrenheit}
onChangeText={handleFahrenheitChange}
accessibilityLabel="Fahrenheit input"
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
padding: 20,
},
label: {
fontSize: 18,
marginTop: 20,
},
input: {
borderWidth: 1,
borderColor: '#999',
padding: 8,
fontSize: 18,
borderRadius: 4,
},
});We keep the temperature value and the scale (which input was last changed) in the parent component's state. When the user types in one input, we update the temperature and scale. Then we convert the temperature to the other scale for the other input. This way, both inputs stay in sync.
We use helper functions to convert between Celsius and Fahrenheit. The inputs accept only numeric values and show the converted temperature rounded to three decimals.
This pattern is called "lifting state up" because the shared state lives in the common parent, not inside each input separately.