AliAb
AliAb

Reputation: 569

Trouble rendering dynamically in react native

I have this function in my react native class:

the Content of Before Button Press shows immediately when the component mounts, but when i press the hello text,the "onPressingTheButton" function is executed and the console shows the logged text and the flag is now 2. the problem is that the "Content After Button Press" is not displayed even after changing the flag.

PastEvents = () => {
    var hello;
    var flag = 1

function onPressingTheButton() {
  console.log("logged text")
  flag = 2
  console.log(flag) //2
}
if (flag == 1) {
  hello = <View>Content Before button Press</View> //displayed
}

if (flag == 2) {
   hello = <View>After Button Press</View> //never displayed
}
  return (
    <View style={styles.container}>
      {hello}
      <TouchableOpacity>
        <Text onPress={() => onPressingTheButton()}>helloo</Text>
      </TouchableOpacity>
    </View>
  )
 }
}

as a note, the past event function is called by a scenemap from the first render :

 render() {
      return (
        <TabView
          navigationState={{ index: this.state.index, routes: this.state.routes }}
          renderScene={SceneMap({
            PastEvents: this.PastEvents,
            UpcomingEvents: this.UpcomingEvents,
          })}
        />
      );
    }

how can I display the "Content After button Press"? Thank you for your help.

Upvotes: 0

Views: 106

Answers (2)

Goskula Jayachandra
Goskula Jayachandra

Reputation: 4201

For this you need to use useState like this:

import React from 'react';
import {View,Text, TouchableOpacity} from 'react-native';
import  {useState} from 'react';

PastEvents = () => {
    const [hello , setText] = useState('Before Button Press');
    var flag = 1

    function onPressingTheButton() {
  console.log("logged text")
  flag = 2
  console.log(flag) //2
  if(flag == 2){
    setText('After Button Press');
  }

}

  return (
    <View style={{marginTop:"30%"}}>
      <Text>{hello}</Text>
        <Text onPress={() => onPressingTheButton()}>helloo</Text>
    </View>
  )
 }
 export default PastEvents;

enter image description here

After Button press

enter image description here

Hope this helps!

Upvotes: 2

kaizen
kaizen

Reputation: 1638

Hi can you try to insert the conditional statements into the onPressingTheButton function.

function onPressingTheButton() {
  console.log("logged text")
  flag = 2
  console.log(flag) //2

  if (flag == 1) {
    hello = <Text>Before button Press</Text> //displayed
  }

  if (flag == 2) {
     hello = <Text>After Button Press</Text> //never displayed
  }

}

Upvotes: 0

Related Questions