Home > Software engineering >  React Native : Return conditional Statement in View
React Native : Return conditional Statement in View

Time:04-25

I'm facing a weird problem. In my react native app I have conditions that render the View and ScrollView. The problem is the false statement shows first before the true statement, so I have example below let say the PinCodeVisible.showPinLock is true so the Pincode should shown not the false statement which is the text. My problem is it shows first the false statement which is the text and then after it loads the true statement which is pincode , I just want to disregard the text under the false statement since it is false,

why It shown even it is false statement? Did I missed something?

const [PinCodeVisible, setPin] = useState({ PINCodeStatus: "choose", showPinLock: false });

React.useEffect(() => {
setPin({ showPinLock: true});   //let say the pincode is true
 }, [])


return (
    <View style={styles.container} >
        {PinCodeVisible.showPinLock === true ? (

            <PINCode
                // modalVisible={modalVisible}
                status={PinCodeVisible.PINCodeStatus}
                touchIDDisabled={true}
                finishProcess={() => _finishProcess()}
                timeLocked={5000}
            />
        ) :
            <ScrollView style={styles.container}> //this scrollview shown first event the statement is true
                <Text>This text will show before the true statement above</Text>  // it should not shown because the statement is true
            </ScrollView>}
    </View>
)

const styles = StyleSheet.create({
  container: {
    flex: 1,
  }

CodePudding user response:

You can check the following things,

  1. Here if you want to display a true statement on page load then must set true as an initial value of your state only not required to set in useEffect.

const [pinCodeVisible, setPin] = useState({ PINCodeStatus: "choose", showPinLock: true });

  1. If you want to update an object then you can update using the spread operator.

setPin({ ... pinCodeVisible, showPinLock: true});

  1. In the render method you can use the conditional operator as below
return (
    <View style={styles.container}>
      {(pinCodeVisible.showPinLock && (
        <PINCode
          finishProcess={() => _finishProcess()}
          status={pinCodeVisible.PINCodeStatus}
          timeLocked={5000}
          touchIDDisabled={true}
        />
      )) || (
        <ScrollView style={styles.container}>
          <Text>This text will show before the true statement above</Text>
        </ScrollView>
      )}
    </View>
   );
  • Related