Reputation: 868
Is there a way I can target views created in react native in JavaScript code akin to what I can do in JavaScript for web? i.e. give an ID to a view and then call document.getElementById
?
What I am trying to achieve is a way to toggle the visibility of a View on a button (TouchableHighlight) tap.
Upvotes: 0
Views: 242
Reputation: 53681
There is a way to target a view or component in React Native, through refs. https://facebook.github.io/react/docs/more-about-refs.html.
But, in your case if what you are trying to do is toggle a view you can achieve this by returning a view based on a state variable being true or false. Something like:
toggleView() {
this.setState({
showView: !this.state.showView
})
}
var view = <View><Text>This view is being toggled</Text></View>
<TouchableHighlight onPress={ () => this.toggleView() } >
<Text>Toggle View</Text>
</TouchableHighlight>
{this.state.showView && view}
There's a working project set up here. Full code is below.
https://rnplay.org/apps/puK5UQ
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} = React;
var SampleApp = React.createClass({
getInitialState() {
return {
showView: true
}
},
toggleView() {
this.setState({
showView: !this.state.showView
})
},
render: function() {
var view = <View style={{height:100, backgroundColor: 'red'}}><Text>This view is being toggled</Text></View>
return (
<View style={styles.container}>
<TouchableHighlight underlayColor="#efefef" onPress={ () => this.toggleView() } style={{marginTop:60, backgroundColor: '#ededed', height:60, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize:20 }}>Toggle View</Text>
</TouchableHighlight>
{this.state.showView && view}
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
Upvotes: 3