Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show button and text in react native

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?

like image 754
CheeseBurger Avatar asked Mar 26 '26 21:03

CheeseBurger


2 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>
like image 116
HichamELBSI Avatar answered Mar 29 '26 12:03

HichamELBSI


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"
    />
</>
like image 25
enzou Avatar answered Mar 29 '26 13:03

enzou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!