Show button and text in react native

Viewed 917

I tried to code in react native today and tried to write a program with a button and a text that changes with every press:

import { Text, View, StyleSheet, TouchableOpacity, Button, TextInput } from 'react-native';
import Constants from 'expo-constants';


export default () => {

const onButton = () =>
{
  myResult(10);
}

return (
  <Text>Hello World</Text>  

  <Button
  onPress={onButton}
  title="Click Here to calculate"
  color="black"
  />
)
}

It gives me this error:

Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

If I comment the text class or the button class like that: //<Text>Hello World</Text> the other class would work.

Any suggestions?

3 Answers

You can't render multiple component like that. Like the error message said, you have to wrap them in an enclosing tag.

<View>
    <Text>Hello World</Text>  

    <Button
      onPress={onButton}
      title="Click Here to calculate"
      color="black"
    />
</View>

You are returning 2 components, in react you must return just one component, so your code you could wrapping in two ways:

<View>
    <Text>Hello World</Text>  

    <Button
      onPress={onButton}
      title="Click Here to calculate"
      color="black"
    />
</View>

Or using Fragment component of react that will no add a node in your component tree

//You can use Fragment as <></> or <React.Fragment></React.Fragment>
<>
    <Text>Hello World</Text>  

    <Button
      onPress={onButton}
      title="Click Here to calculate"
      color="black"
    />
</>

The best option is to wrap it in a <View> tag, as mentioned in the other two answers.


Here is a fun solution, you can even return an array.

Example:

return [
        <Text>Hello World</Text>, 
        <Button 
           onPress={onButton}
           title="Click Here to calculate"
           color="black" 
        />
];
Related