I am trying to use an inline if statement to check if a piece of data exists and if it does to display it. this code is currently sitting in my render, return block.
the problem I am having is that using this, the content is no longer being rendered
{(() => {
if (this.props.data.size) {
<Text style={styles.headerLabel}>Sizes</Text>
{(this.props.data.size||[]).map((section,i) => (
<AddToCartRow key={i} data={section} productName={this.props.data.name} value={Config.priceToPriceWithCurrency(section.price)} />
))}
}
})()}
In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.
Editor's note: This tutorial was last updated on 16 June 2022 to reflect changes made in React v18. JSX is a powerful extension to JavaScript that allows us to define UI components.
Logical && Operator Another way to conditionally render a React component is by using the && operator.
This below code also check empty string.
render(){
return(
<View>
{!!this.state.error && <Text>{this.state.errorMessage}</Text>}
</View>
);
}
render(){
return(
<View>
{this.state.error && <Text style={{ color: 'red' }}>{this.state.errorMessage}</Text>}
<Text>Hello World!</Text>
</View>
);
}
There you go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With