Theodor Suciu
Theodor Suciu

Reputation: 51

How to implement "if else" condition in react native

I am building a simple counter application that can increase or decrease the "streak" number (total number). The increase/ decrease buttons work however, I am having difficulty implementing if/else logic. As you can see in the code I am trying to return a message "CongratsGreeting" whenever the "streak" counter reaches a value of 10.

    function CongratsGreeting(props) {
        return <h1>Congrats on reaching 10!</h1>; 
    } 

const CounterScreen = () => {
    const [counter, setCounter] = useState(0);

    return <View style={styles.container}>
        <Button title="Increase" color='#0d97a6' onPress={() => {
            setCounter(counter + 1);
            if (counter == 10) {
                return <CongratsGreeting />;
            }
         }} />
         <Button title="Decrease" color='#0d97a6' onPress={() => {
             setCounter(counter - 1);
         }} />
          <Text style={styles.streak}>Streak: {counter}</Text>
     </View>
};

Upvotes: 0

Views: 512

Answers (2)

Flagship1442
Flagship1442

Reputation: 1726

I think you got a little confused. onPress can execute some code but it can't return a JSX component like this (at least doing so does nothing).

Instead you need to render that component with its visibility dependent on your counter state.

Something like this:

const CongratsGreeting = props => {
  if (!props.visible) return null;

  return <Text>Congrats on reaching 10!</Text>; // Use `Text` instead of h1
};

const CounterScreen = () => {
  const [counter, setCounter] = useState(0);

  return (
    <View style={styles.container}>
      <CongratsGreeting visible={counter === 10} />
      <Button title='Increase' color='#0d97a6' onPress={() => setCounter(counter + 1)} />
      <Button title='Decrease' color='#0d97a6' onPress={() => setCounter(counter - 1)} />
      <Text style={styles.streak}>Streak: {counter}</Text>
    </View>
  );
};

Upvotes: 1

   function CongratsGreeting(props) {
        return <h1>Congrats on reaching 10!</h1>; 
    } 

const CounterScreen = () => {
    const [counter, setCounter] = useState(0);

    return 
     <View>
      {counter==10 && <CongratsGreeting />}
      <View style={styles.container}>
        <Button title="Increase" color='#0d97a6' onPress={() => {
            setCounter(counter + 1);
         }} />
         <Button title="Decrease" color='#0d97a6' onPress={() => {
             setCounter(counter - 1);
         }} />
          <Text style={styles.streak}>Streak: {counter}</Text>
     </View>
    </View>
};

Upvotes: 1

Related Questions