Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue on Hide/Show component in React Native

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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 🙂

>Solution :

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
        }; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading