I am doing a weather app using React-Native now Iam trying to Fetch the data of the API so Created a file WeatherData.js that return the name, temp and Weather.
I want to pass the data to a Component called title it won’t work
WeatherData.js
return (
<View>
{weatherData ? (
<View>
<Title
name={weatherData?.name}
temperature={weatherData?.main?.temp}
description={weatherData?.weather[0]?.description}
/>
console.log({weatherData})
</View>
) : (
<Text>No weather data available</Text>
)}
</View>
);
};
export default Data;
Title.tsx
here is an example to pass the name prop
import { Text } from "react-native";
import { View, StyleSheet, StatusBar } from "react-native";
const Title = ({ name }) => {
return (
<View style={FontStyle.Align}>
<Text style={FontStyle.Bold} >{name}</Text>
<Text style={FontStyle.Thin} >Tue, Jun 30</Text>
</View>
);
}
export default Title;
2
Answers
If you want to use ternary operator make sure to pass a
boolean
to the first argument.So instead of writing
{weatherData ? ... : ...}
it is better to convert it to boolean like{!!weatherData}
.Secondly, you need to put the curly braces to run it as JS command.
Otherwise it will be rendered as text.
Most probably the variable weatherData will be holding an empty object.
An empty object is not a falsy value. Please see the expression below which evaluates to true.
Therefore the component does not return the jsx having the string "No weather data available".
However, every reference of the properties in an empty object will yield undefined. Therefore the following expression evaluates to falsy. The Text component will ignore falsy values which will eventually give us an impression that the custom component Title does not work.
As a solution, please diagonose and fix the reasons to get an empty object.