Home > Software design >  I am trying to get this if-else statement working in ReactNative
I am trying to get this if-else statement working in ReactNative

Time:03-10

The goal right now is when they press the button for it to test to see if the inputs have the correct values in them (user and password) if so run the if part of the statement and succeed, otherwise run the fail statement. It keeps giving me formatting errors and this is the first time doing if-else statements on react-native. Again just want to figure out the if-else statement I have tried all the ways I know from Java and Matlab. I also have seen a lot of other answers but from what I can tell they require a function to be called upon but don't explain how to set up that function.

import { StyleSheet, Text, Button, SafeAreaView, TextInput, Image, Alert} from 'react-native';

export default function App() {
const [text, onChangeText] = React.useState(null);
const [name, setname] = useState (null);
const [password, setpassword] = useState ('')

function SuccessGreeting() {
  return Alert.alert('Placeholder Success')
}
function FailGreeting() {
  return Alert.alert('Failed Placeholder')
}

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.Text}>
        Hello! Welcome to the Popgrammers app.
      </Text>
      <Text style={styles.Text}>
        Please Log In.
      </Text>
      <TextInput
        style = {styles.input}
        onChangeText={(name) => setname(name)}
        placeholder = "Enter Username"
        />
      <TextInput
      style = {styles.input}
      onChangeText ={(password) => setpassword (password)}
      placeholder = "Enter Password"
      />
      <Button
        onPress= {
          if (this.name.value == "User") {
            return <SuccessGreeting />;
          },
          else{
            return <FailGreeting/>;
          } 

        title="Log In"
        color="red"
      />
    </SafeAreaView>
  );
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'cornflowerblue',
    alignItems: 'center',
    justifyContent: 'center',
  }, 
 input: {
    borderWidth: 1,
    borderColor: '#777',
    padding: 8,
    margin: 10,
    width: 200,
    justifyContent: 'center',
},
  container1: {
    flex: 1,
    justifyContent: 'center',
    marginHorizontal: 200,
  },
  Text: {
    fontSize: 14,
    color: 'red',
    textAlign: 'center',
  }
}); 

CodePudding user response:

There are many things that you are doing wrong here. First of all, you have not imported the packages that you are using. So import those packages. For your code, React and useState is missing. Import as below:

import React, { useState } from "react";

Second, the method name should start with lowercase(as react standard).

So declare your methods as below:

function successGreeting () {
  return Alert.alert('Placeholder Success');
}

function failGreeting () {
  return Alert.alert('Failed Placeholder');
}

Now, create a method which will be called on onPress of button and write your if else statement in that method. Then call that method on onPress of the button like this:

// method declaration
function onLoginPress () {
  if (name === "User") {
    successGreeting();
  } else {
    failGreeting();
  }
}

// call method
<Button
  onPress={onLoginPress}
  title="Log In"
  color="red"
/>

Also, you can access state variables directly without using this. And your name state will be just string so instead of checking name.value === "User", just check name === "User".

Your whole code should be this:

import React, { useState } from "react";
import { StyleSheet, Text, Button, SafeAreaView, TextInput, Image, Alert } from 'react-native';

export default function App () {
  const [text, onChangeText] = React.useState(null);
  const [name, setname] = useState(null);
  const [password, setpassword] = useState('');

  function successGreeting () {
    return Alert.alert('Placeholder Success');
  }

  function failGreeting () {
    return Alert.alert('Failed Placeholder');
  }

  function onLoginPress () {
    if (name === "User") {
      successGreeting();
    } else {
      failGreeting();
    }
  }

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.Text}>
        Hello! Welcome to the Popgrammers app.
      </Text>
      <Text style={styles.Text}>
        Please Log In.
      </Text>
      <TextInput
        style={styles.input}
        onChangeText={(name) => setname(name)}
        placeholder="Enter Username"
      />
      <TextInput
        style={styles.input}
        onChangeText={(password) => setpassword(password)}
        placeholder="Enter Password"
      />
      <Button
        onPress={onLoginPress}
        title="Log In"
        color="red"
      />
    </SafeAreaView>
  );
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'cornflowerblue',
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
    borderWidth: 1,
    borderColor: '#777',
    padding: 8,
    margin: 10,
    width: 200,
    justifyContent: 'center',
  },
  container1: {
    flex: 1,
    justifyContent: 'center',
    marginHorizontal: 200,
  },
  Text: {
    fontSize: 14,
    color: 'red',
    textAlign: 'center',
  }
}); 

CodePudding user response:

<Button
  onPress={() => {
    this.name.value == "User" ? SuccessGreeting() : FailGreeting();
  }}
  title="Log In"
  color="red"
/>

CodePudding user response:

I would like to add something to Kishan Bharda's answer.

Judging from your code, you might be mixing up JSX functional components and JS functions. If we write

function SuccessGreeting() {
  return <Text>Greeting</Text>
}
function FailGreeting() {
  return <Text>This has failed</Text>
}

then these are JSX functional components that return a react-native Text component and we can render it in a screen using

<SuccessGreeting />
<FailGreeting />

(in this case it is standard to start the function name with a capital letter)

The nice thing about JSX is that we can mix in Javascript, e.g. for conditionally rendering components. Here is an example.

return (
    <SafeAreaView style={styles.container}>
        {
             name === "User" ? <SuccessGreeting /> : <FailGreeting />
        }  
    </SafeAreaView>
)

In the return function of a functional component, we can conditionally rendering the component SuccessGreeting or FailGreeting by testing if the state variable name is equal to the string "User".

Notice, that you need curly braces ("{}") in order to start a Javascript statement inside a JSX render method.

The other things are already pointed out by Kishan Bharda, e.g. returning a JSX component inside the onPress function of a Button is not possible, e.g.

<Button
        onPress= {
          if (this.name.value == "User") {
            return <SuccessGreeting />;
          },
          else{
            return <FailGreeting/>;
          } 

        title="Log In"
        color="red"
/>

is not possible. It is also not possible to write

<SuccessGreeting />

at all if the function SuccessGreeting does not return a JSX. Your current function

function SuccessGreeting() {
  return Alert.alert('Placeholder Success')
}

is just a plain JS function. It has nothing to do with react native, but since you are writing Placeholder here you might meant to return an actual JSX component here.

  • Related