Search code examples
javascriptreact-nativejsx

"Text strings must be rendered within a <Text> component"


I've upgraded from React Native 0.54 to 0.57 and my application has fallen over, due to using React Native elements.

I used the error functionality of TextInput components, which enabled props that can set and style the error message.
Very convenient, but the upgrade has broken these, and I'm now greeted with this error:

Invariant Violation: Text strings must be rendered within a <Text> Component.

Invariant Violation: Text strings must be rendered within a  Component.

So I've deleted that code and the error disappears.
However, I'm still receiving the issue when I run this code:

{ this.state.event.cards[i].fields[j].error && 

  <Text style={{ color: '#e74c3c', fontSize: 14, paddingLeft: 5 }}>
    {this.state.event.cards[i].fields[j].error}
  </Text>
}

When I begin typing in the text-input, it sets the error message to an empty string.
So if an error is returned, typing in the field will make the error go away.

My goal is to check if this.state.event.cards[i].fields[j].error is a non-empty string, and if so, display it.


Solution

  • For me the following code works fine, as long as this.state.error === undefined or it is not an empty string.

    render() {
      return (
        <View>
          {this.state.error &&
    
            <Text>
              Error message: {this.state.error}
            </Text>
          }
        </View>
      );
    }
    

    If the error state is changed to empty string '', you will have the aforementioned exception: Invariant Violation: Text strings must be rendered within a <Text> component

    The reason of that is, when this.state.error === '', the following expression will be evaluated as empty string, i.e., '', and this will cause Invariant Violation: Text strings must be rendered within a <Text> component

    {this.state.error &&
    
      <Text>
        Error message: {this.state.error}
      </Text>
    }
    

    When this.state.error === undefined, the expression will be evaluated as undefined, which is what we expect, and it's fine.