Home > Enterprise >  Issue on Hide/Show component in React Native
Issue on Hide/Show component in React Native

Time:08-27

I am new in React native development and i am trying to do something simple. I have 4 components <TouchableOpacity> in a React Class extending Component.

In the render function, i am trying to hide three of these components while i am pressing on one.

render(){ 
[...]
return (
    <TouchableOpacity style={styles.filterButtonAll} onPress={()=>this.toggleStatus()}>
      <Ionicons size={15} name='XXX'>  Show/Hide</Ionicons>
    </TouchableOpacity>
            
    <TouchableOpacity style={styles.filterButton}>
      <Ionicons size={15} name='XXX'>  Text1</Ionicons>
    </TouchableOpacity>
    <TouchableOpacity style={styles.filterButton}>
      <Ionicons size={15} name='XXX'>  Text2</Ionicons>
    </TouchableOpacity>

    <TouchableOpacity style={styles.filterButton}>
      <Ionicons size={15} name='XXX'>  Text3</Ionicons>
    </TouchableOpacity>
    [...]
    )
}

toggleStatus function :

  toggleStatus(){
      this.state.showMenu = !this.state.showMenu;
    };  

And i have my showMenu in my state.

I tried conditional, and many other things following many posts about this subject, but when i am logging {this.state.showMenu} , it is dynamic in my toggleStatus() function but it's always the same value in my render function.

I think i am doing something wrong, thanks in advance for your help :)

CodePudding user response:

The way your updating your state is incorrect. You have to call a function called setState() and then pass the updated state.

Reference for setState: https://reactjs.org/docs/react-component.html#setstate.

Example:

toggleStatus(){
        this.setState({showMenu : !this.state.showMenu}); // RIGHT
       // this.state.showMenu = !this.state.showMenu; // WRONG
    }; 

Recommend way: basically when your state update depend upon the previous state its better to use this approach.

toggleStatus(){
             this.setState((state, props) => {
              return {showMenu: !state.showMenu};
            });
           
           // this.state.showMenu = !this.state.showMenu; // WRONG
        }; 
  • Related