0

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>
};
1
  • is CongratsGreeting a separate component? Commented Apr 8, 2020 at 8:57

2 Answers 2

1

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>
  );
};
Sign up to request clarification or add additional context in comments.

Comments

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>
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.