Reputation: 1
I am creating a weather app using React Native. I am trying to Fetch the data of the API, so I created a file WeatherData.js
that returns the name, temp and Weather.
I want to pass the data to a Component called title but this doesn'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;
Upvotes: 0
Views: 30
Reputation: 1954
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.
{} ? 'not falsy' : 'falsy' // not falsy
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.
{}.name ? 'not falsy' : 'falsy' // falsy
As a solution, please diagonose and fix the reasons to get an empty object.
Upvotes: 0
Reputation: 1077
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.
// Rendered as Text
console.log(...)
// Rendered as JS
{console.log(...)}
Otherwise it will be rendered as text.
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>
);
Upvotes: 0