React Native
Display
Display the temperature and condition.
Display the temperature
Now we have a weather state. It is time to show it on the screen. We use a large <Text> for the temperature and another <Text> for the condition.
The temperature label looks like this: <Text style={'{ styles.temp }'}>{`{weather.temp}°C`}</Text>. Here {`{weather.temp}`} pulls the value from state and °C adds the unit next to it.
Similar labels go for the city and condition. We build a hierarchy with fontSize and fontWeight; the temperature is the largest, the city and condition are smaller.
Styling the weather card
To emphasize the temperature we use a large font: fontSize: 64. The city gets a medium size: fontSize: 24. The condition is smaller: fontSize: 18, gray.
Each Text gets its own style. Inside StyleSheet.create we define three keys: city, temp and condition. This keeps the code tidy.
We can also add color: color: '#333'. This is a light gray tone; it improves readability. Later, when we add a background image, we may switch to white.
Exercise Show the weather card
Add three <Text> tags to the skeleton: city, temperature and condition. They should show {`{weather.city}`}, {`{weather.temp}°C`} and {`{weather.condition}`} in order. Give each a style from StyleSheet.create (styles.city, styles.temp, styles.condition). The temp style should have fontSize: 64. Export the App function.
Show example solution
import { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
function App() {
const [weather, setWeather] = useState({ city: 'London', temp: 14, condition: 'Cloudy' });
return (
<View style={styles.container}>
<Text style={styles.city}>{weather.city}</Text>
<Text style={styles.temp}>{weather.temp}°C</Text>
<Text style={styles.condition}>{weather.condition}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
city: { fontSize: 24, marginBottom: 8 },
temp: { fontSize: 64, fontWeight: 'bold' },
condition: { fontSize: 18, color: '#555' }
});
export default App;
Test yourself
-
How is the temperature shown?
- <Text>{weather.temp}°C</Text>
- <Text>weather</Text>
- <View>temp</View>
- <Text>temp</Text>
Show answer
<Text>temp</Text> — weather.temp is evaluated inside curly braces.
-
Match the display parts
- weather.temp
- Temperature value
- weather.city
- City name
- weather.condition
- Condition
- fontSize: 64
- Temperature style
-
Styled temperature Text
import { Text } from 'react-native';
function App() {
return (
<Text style={{ fontSize: ____ }}>{weather.temp}°C</Text>
);
}
Show answer
import { Text } from 'react-native';
function App() {
return (
<Text style={{ fontSize: 64 }}>{weather.temp}°C</Text>
);
}
Next lesson: City selection