skip to Main Content
if (condition works){
  let x = 20;
  let y= 30;
  console.log(x);
  console.log(y);
}  

using react native:
I don’t want to declare the variable outside the if condition so I use the let inside the if statement. Now, I want to call this outside of the if statement in return (),

How can I call the x, y in return and get the values?

suppose:

return (
  <View style={styles.container}>
    <Text style={styles.text}>
       X:{x} & Y:{y} 
    </Text>
  </View>
);

2

Answers


  1. Akash Ghosh, this is not the right approach. You should save your x and y in useState, and show them if your condition is met, smt like this:

    const [x,setX]=useState(null);
    const [y,setY]=useState(null);
    

    And in you function you just set the value:

        if(conditionMet){
         setX(20);
         setY(30);
        }
    

    And in your rendering if you don’t want to show them if they value didn’t change you do this:

    return (
      <View style={styles.container}>
      { x && y ? <Text style={styles.text}>
        X:{x} & Y:{y} 
      </Text> :null }
    
      </View>
    );
    
    enter code here
    
    Login or Signup to reply.
  2.  you can define like it  
    
    
    function myfunction (){
        if (condition works){
                    let x = 20;
                    let y= 30;
                    let data={x,y}
                    return data
                 }
    }
    

    and can use like it

    return (
      <View style={styles.container}>
      { x && y ? <Text style={styles.text}>
        X:{myfunction().x} & Y:{myfunction().y} 
      </Text> :null }
    
      </View>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search