Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle visibility for React Native elements?

Tags:

react-native

In React Native, is there a way to toggle visibility of an element?

For example:

<Text visibility={this.state.isVisible}>Visibility depends on state</Text>
like image 422
Some Guy Avatar asked Oct 19 '22 04:10

Some Guy


2 Answers

this might be crude but it works.

under render

var visibletext = null;
if (this.state.isVisible) {
   visibletext = (<Text>Visibility depends on state</Text>);
} 

then, under return part

<View style={styles.container}>
   {visibletext}
</View>
like image 104
boredgames Avatar answered Oct 22 '22 03:10

boredgames


There are various ways to do this. See the Conditional Rendering guide at the React.js website, which explains different options.

One simple way is to use the && operator inline:

{this.state.isVisible &&
  <Text>Something</Text>
}

Note that with the conditional rendering approach, if you have (for example) some views centered vertically, this views will suddenly move up or down when the text appears (to give room for the new view). Another approach that avoids this jump is to either change the text color or set the text to empty string:

// Change the text color
<Text style={this.state.isVisible ? {color: 'black'} : {color: 'white'}}>Something</Text>

// Set text to empty string
<Text>{this.state.isVisible ? "Something" : ""}</Text>

Changing the color of the text is the best way to make sure that the other views don't suddenly move when showing the text, given that the text is already occupying the layout space it needs.

like image 39
Albert Vila Calvo Avatar answered Oct 22 '22 03:10

Albert Vila Calvo