close

[Solved] Invariant Violation: Text strings must be rendered within a Text component

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Invariant Violation: Text strings must be rendered within a Text component in react-native. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How To Solve Invariant Violation: Text strings must be rendered within a Text component Error ?

  1. How To Solve Invariant Violation: Text strings must be rendered within a Text component Error?

    To Solve Invariant Violation: Text strings must be rendered within a Text component Error Here the following code works fine, as long as this.state.error === undefined or it is not an empty string. The reason for that is, when this.state.error === '', the following expression will be evaluated as an empty string, i.e., '', and this will cause Invariant Violation: Text strings must be rendered within a component

  2. Invariant Violation: Text strings must be rendered within a Text component

    To Solve Invariant Violation: Text strings must be rendered within a Text component Error Here the following code works fine, as long as this.state.error === undefined or it is not an empty string. The reason for that is, when this.state.error === '', the following expression will be evaluated as an empty string, i.e., '', and this will cause Invariant Violation: Text strings must be rendered within a component

Solution 1

Here 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 the empty string ”, you will have the aforementioned exception: Invariant Violation: Text strings must be rendered within a <Text> component

The reason for that is, when this.state.error === '', the following expression will be evaluated as an 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.

Solution 2

I’d use !! which I call bang bang operator to boolianize error. That should work.

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

If error is a string, whatever your text should be wrapped with <Text /> as the error message says in React Native, which is different from web.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment