Wednesday, February 6, 2019

How to resolve "Invariant Violation: Text strings must be rendered within a component" error message during the React development?

Software Required
NPM version 6.4.1
expo version 2.6.14
Atom 1.34.0
NativeBase 2.10.0. Please refer to link

Problems

  • Run through NativeBase tutorial on Button, encounter the error message . Please refer to the screenshot below.
  • Below are my original source code
import React, { Component } from 'react';
import { Container, Header, Content, Button, Text } from 'native-base';
import {Font, Expo, AppLoading} from 'expo';

class ButtonSizeExample extends Component {
  state={
    isReady: false
  }

  async componentWillMount() {
    await Font.loadAsync({
      'Roboto': require('native-base/Fonts/Roboto.ttf'),
      'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'),
    });
    this.setState({isReady:true})
  }

  render() {
    if (!this.state.isReady) {
      return <AppLoading />;
    }

    return (
      <Container>
        <Header />
        <Content>
          /*Small size button*/
          <Button small primary>
            <Text>Default Small</Text>
          </Button>
          /*Regular size button*/
          <Button success>
            <Text>Success Default</Text>
          </Button>
          /*Large size button*/
          <Button large dark>
            <Text>Dark Large</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}
export default ButtonSizeExample;
Steps
  • The root cause of the problem is caused by the comment /* Small ...*/ in the source code.

    return (
      <Container>
        <Header />
        <Content>
          /*Small size button*/
          ...
          /*Regular size button*/
          ...
          /*Large size button*/
          ...
        </Content>
      </Container>
    );
  }
}
export default ButtonSizeExample;
  • Remove those comment, it will work like a charm.
import React, { Component } from 'react';
import { Container, Header, Content, Button, Text } from 'native-base';
import {Font, Expo, AppLoading} from 'expo';

class ButtonSizeExample extends Component {
  state={
    isReady: false
  }

  async componentWillMount() {
    await Font.loadAsync({
      'Roboto': require('native-base/Fonts/Roboto.ttf'),
      'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'),
    });
    this.setState({isReady:true})
  }

  render() {
    if (!this.state.isReady) {
      return <AppLoading />;
    }

    return (
      <Container>
        <Header />
        <Content>
          <Button small primary>
            <Text>Default Small</Text>
          </Button>
          <Button success>
            <Text>Success Default</Text>
          </Button>
          <Button large dark>
            <Text>Dark Large</Text>
          </Button>
        </Content>
      </Container>
    );
  }
}
export default ButtonSizeExample;

No comments: