18

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)} />
                ))}
              }
            })()}
Boss Nass
  • 3,384
  • 9
  • 48
  • 90
  • You forgot to return the component – binchik Feb 07 '17 at 14:49
  • You might want to check this [post](http://stackoverflow.com/questions/42053237/is-it-possible-to-dynamically-create-components-in-react-native/42057846#42057846). – milkersarac Feb 07 '17 at 20:01
  • hi, this is already within a render and return block complete code is here https://gist.github.com/pmcguane/6462dad133543dc6d91f3645b3ec0bf5 – Boss Nass Feb 08 '17 at 10:31
  • 1
    @milkersarac this doesn't really help as this would cause the heading to be repeated over and over again – Boss Nass Feb 11 '17 at 11:59

4 Answers4

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

There you go.

Juan Antonio
  • 2,451
  • 3
  • 24
  • 34
Ata Mohammadi
  • 3,430
  • 6
  • 41
  • 69
  • Oh sorry. I just clicked the *"Run code snippet"* button above and the result showed an error. But I think it's nothing to do with your code. Sorry. – Giraldi Aug 14 '17 at 09:33
8

This below code also check empty string.

render(){
  return(
    <View>
    {!!this.state.error && <Text>{this.state.errorMessage}</Text>}
    </View>
  );
}
Sanjib Debnath
  • 3,556
  • 2
  • 22
  • 16
0

Try use this eslint Rules:

"no-restricted-syntax": [
  "error",

  ...otherRules,

  // Two rules below help us avoid this common point of confusion: https://stackoverflow.com/q/53048037
  // The selectors are inspired by https://github.com/yannickcr/eslint-plugin-react/issues/2073#issuecomment-844344470
  {
    selector:
      ":matches(JSXElement, JSXFragment) > JSXExpressionContainer > LogicalExpression[operator='&&']",
    message:
      "Please use `condition ? <Jsx /> : null`. Otherwise, there is a chance of rendering '0' instead of '' in some cases. Context: https://stackoverflow.com/q/53048037",
  },
  {
    selector:
      ":matches(JSXElement, JSXFragment) > JSXExpressionContainer > LogicalExpression[operator='||']",
    message:
      "Please use `value ?? fallbackValue`. Otherwise, there is a chance of rendering '0' instead of '' in some cases. Context: https://stackoverflow.com/q/53048037",
  },
],

Link: https://github.com/yannickcr/eslint-plugin-react/issues/2073#issuecomment-864168062

Dung Nguyen
  • 181
  • 1
  • 5
0

In general, conditional rendering in React Native is the same as in React. But be aware that in React Native we can render strings only inside the Text component. So, for example, if we will try to put a string inside a View it will throw an error.

Inline if with logical && operator.

<View>
  {!!error && <ErrorMessage />}
</View>

⚠️ Double negation !! operator is very important here (also we can use the Boolean function) because it ensures that the left part of the condition will be a boolean value.

Why it is important? Because logical “and” operator && will return the right side of the condition if the left side is truthy, and will return the left side of the condition if the left side is falsy.

Imaging we have a component:

<View>
  {error && <ErrorMessage />}
</View>

If the error variable will be an object / null / undefined everything will work as expected. But if we will get an empty string for the error ( error = '' ) then our component will brake, because we can’t render strings inside a View component.

// error = ''
// {error && <something>} will return the error variable (which equals to '')
// and we will get:
<View>
  ''
</View>
// which will throw an error (can't render strings inside a View )

Inline if-else with ternary ? operator.

{error ? <ErrorMessage /> : <SuccessMessage />}

or

{error ? <ErrorMessage /> : null}

Here we can return null or <></> (React Fragment) depend on our component structure and return type.

if statement

...

const Error = () => {
  if (!error) {
    return null
  }

  return <ErrorMessage />
}

return (
  <View>
    <Error />
  </View>
)

Code example

Please use this Expo Snack to see the full code and play with it.

Vladimir Vovk
  • 688
  • 8
  • 9