Home > other >  How to add button to React Native
How to add button to React Native

Time:10-11

I'm very new to react native and am trying to add a button to this page. I'm not very sure exactly where to place the code because I keep getting the error "Adjacent JSX elements must be wrapped in enclosing tag." Any help would be very appreciated.

function Expenses() {

  return (
    
  <View style={styles.settings}>
    <Button 
    title="Am I overbudget?"
    onPress={
      () => Alert.alert(
        'No you are not overbudget !')}
        />
        </View>
    
    <View style={styles.container}>
      <TextInput style={styles.input} placeholder="Input Expenses"  />
      <TextInput style={styles.input} />
      <Text>Expenses</Text>
    </View>
    
  );
  
};

CodePudding user response:

The problem is because you are trying to render multiple views within the component. There can only be one top-level element. To fix this issue you can either wrap the sub views with a parent view or with react fragments.

function Expenses() {

  return (
    <>
  <View style={styles.settings}>
    <Button 
    title="Am I overbudget?"
    onPress={
      () => Alert.alert(
        'No you are not overbudget !')}
        />
        </View>
        
    
    <View style={styles.container}>
      <TextInput style={styles.input} placeholder="Input Expenses"  />
      <TextInput style={styles.input} />
      <Text>Expenses</Text>
    </View>
      </>
  );
  
}

CodePudding user response:

The error you're getting is because you can only have a single top-level element, and you have two Views at the moment. One way to fix it is to wrap the whole JSX code in another View.

Something like this

function Expenses() {

  return (
    <View>
      <View style={styles.settings}>
        <Button 
         title="Am I overbudget?"
         onPress={
          () => Alert.alert(
          'No you are not overbudget !')}
        />
      </View>
    
      <View style={styles.container}>
        <TextInput style={styles.input} placeholder="Input Expenses"  />
        <TextInput style={styles.input} />
        <Text>Expenses</Text>
      </View>
    </View>
  );
  
};
  • Related