9

I went to render a component using Ternary expression.

Currently I a doing something like this

 <View style={container}>
          { this.state.loaded ? 
                            (<VictoryChart
                    theme={VictoryTheme.material}
                    >
                    <VictoryArea
                        style={{ data: { fill: "#c43a31" } }}
                        data={this.coinHistoryData} 
                        x="cHT"
                        y="cHTVU"
                        domain={{ y: [0, 30000] }}
                    />
                    </VictoryChart>)
          : (<Text> Loading..</Text>)}  </View>

But this isn't working and Throwing an error saying Invariant Violation

ExceptionsManager.js:84 Unhandled JS Exception: Invariant Violation: Invariant Violation: Text strings must be rendered within a component.

[Question:] How Can I fix it and render an entire component inside Ternary expression

Ps: According to this stackoverflow question: This happens when we do inline conditional rendering.

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210

1 Answers1

7

I've seen it before in react-native.
There are 2 reasons i know of that will throw this error:

  1. returning null / undefined (not your case i think)
  2. spaces after the </Text> tag (i think this is it in your case)

So remove the spaces in the end:

<View style={container}>
          { this.state.loaded ? 
                            (<VictoryChart
                    theme={VictoryTheme.material}
                    >
                    <VictoryArea
                        style={{ data: { fill: "#c43a31" } }}
                        data={this.coinHistoryData} 
                        x="cHT"
                        y="cHTVU"
                        domain={{ y: [0, 30000] }}
                    />
                    </VictoryChart>)
          : (<Text> Loading..</Text>)}  </View> //<--- spaces are here

So this line

: (<Text> Loading..</Text>)}  </View> 

Should be like this

: (<Text> Loading..</Text>)}</View> 
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • ...and that's why pattern `{condition && ()}{!condition && ()}` look safer for React Native. No extra text put by accident :) – skyboyer Sep 17 '18 at 21:19