Home > Net >  Identifier expected when using if (button_count == 2) {}
Identifier expected when using if (button_count == 2) {}

Time:03-15

I don't know how to fix this error

The if statement shows no errors when it's not in the button, however when I run it on Android it shows render error (too many re-renders)

This is my code:

import React, { Component, useState } from 'react';
import { Button, StyleSheet, Text, TextInput, View } from 'react-native';

export default function App() {
    var button_count
    const [outputText, setOutputText] = useState("You can change this text")
    return (
      <View style={styles.container}>
        <View style={styles.buttonContainer}>
          <Text>{outputText}</Text>
          <Button
            title="Change text"
            onPress={() => {setOutputText('The text changed!'); button_count  = 1}}
            color="#57a9af" 
          />
          if (button_count == 2) {
              setOutputText("It changed again!")
            }
            else if (button_count == 3) {
              setOutputText("Stop doing that")
            }
            else if (button_count == 4) {
              setOutputText("I'm not gonna answer anymore")
            }
        </View>
      </View>
    );
  }

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#d6f0f2',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

CodePudding user response:

You cannot use If in render. You can use

{button_count === 2 ? <Text>Some text</Text> : <Text>Some other text</Text>}

But for your example, the approach is not correct. You can try this one For button_count, create state const [button_count, setbuttoncount] = useState(0);

then in,

useEffect(() => if(button_count === 2) setoutputText('Change text');
,[button_count])

CodePudding user response:

//You should avoid using var and replace it with this
const [button_count, setButtonCount] = useState(0)

//add this useEffect which will run on first render and whenever button_count changes,
//and since the changing of text is a side effect of count increasing, it should be handled here

useEffect(()=>{
  if (button_count==1){
        setOutputText('The text changed!'); 
  }
  else if (button_count == 2) {
        setOutputText("It changed again!")
  }
  else if (button_count == 3) {
     setOutputText("Stop doing that")
  }
  else if (button_count == 4) {
     setOutputText("I'm not gonna answer anymore")
  }
},[button_count])

//in onPress you can now do this
onPress={() => {setButtonCount(button_count 1)}}
  • Related