Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react native conditional rendering

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)} />
                ))}
              }
            })()}
like image 219
Boss Nass Avatar asked Feb 07 '17 11:02

Boss Nass


People also ask

What is conditional rendering in react native?

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.

How many ways you can conditionally render in React?

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.

Which operator can be used to conditionally render a React Component :: || && next?

Logical && Operator Another way to conditionally render a React component is by using the && operator.


2 Answers

This below code also check empty string.

render(){
  return(
    <View>
    {!!this.state.error && <Text>{this.state.errorMessage}</Text>}
    </View>
  );
}
like image 65
Sanjib Debnath Avatar answered Oct 12 '22 11:10

Sanjib Debnath


render(){
  return(
    <View>
      {this.state.error && <Text style={{ color: 'red' }}>{this.state.errorMessage}</Text>}
      <Text>Hello World!</Text>
    </View>
  );
}

There you go.

like image 26
Ata Mohammadi Avatar answered Oct 12 '22 11:10

Ata Mohammadi