Exception When Trying to Create Button - Invariant Violation: Text strings must be rendered within a <Text> component

Viewed 55

I'm learning react native. I have a blank project set up using expo-cli. I have the expo app on my iPhone and am testing the app there. I am, sadly, failing to create a simple button.

First I start with a hello world app, which is working. Here is my App.js file simply displaying hello world:

import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {Button} from "react-native-web";

export default function App() {
  const [outputText, setOutputText] = useState("Hello, world!");
  return (
      <View style={styles.container}>
        <Text>{outputText}</Text>
      </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

To add a Button that will change the text, I add the following line:

<Button onPress={() => setOutputText("The text changed!")} title="Change Text"/>

So now my App.js looks like this:

import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import {Button} from "react-native-web";

export default function App() {
  const [outputText, setOutputText] = useState("Hello, world!");
  return (
      <View style={styles.container}>
        <Text>{outputText}</Text>
        <Button onPress={() => setOutputText("The text changed!")} title="Change Text"/>
      </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

I refresh my app and now I encounter the following error, shown on my phone:

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

What have I done wrong?

1 Answers

Apparently, the problem was with the Button import because of react-dom(package required by react-native-web). I tried using the Button from react-native and your entire logic/code worked fine.

Remove the import

import {Button} from "react-native-web";

And import Button from react-native as such

import { StyleSheet, Text, View, Button } from 'react-native';
Related