Monday, May 13, 2024
136
rated 0 times [  137] [ 1]  / answers: 1 / hits: 36207  / 8 Years ago, thu, february 18, 2016, 12:00:00

Suppose I have a simple React Native app like so:



'use strict';

var React = require('react-native');
var {
AppRegistry,
Text,
TouchableHighlight,
View,
} = React;

var ReactProject = React.createClass({
_onPressOut: function() {
// What do we do here?
},

render() {
return (
<View>
<Text>This text should be before</Text>
<Text>This text should be after</Text>
<TouchableHighlight onPressOut={this._onPressOut}>
<Text>Tap Me</Text>
</TouchableHighlight>
</View>
);
}
});

AppRegistry.registerComponent('ReactProject', () => ReactProject);


How can I dynamically insert a component between the first and second Text tags when the TouchableHighlight is pressed?


More From » react-native

 Answers
-1

Try creating an array and attaching it to the state. You can then push items to the array, and reset the state.



https://rnplay.org/apps/ymjNxQ



'use strict';

var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} = React;

var index = 0

var SampleApp = React.createClass({

getInitialState(){
return { myArr: [] }
},

_onPressOut() {
let temp = index ++
this.state.myArr.push(temp)
this.setState({
myArr: this.state.myArr
})
},

render() {

let Arr = this.state.myArr.map((a, i) => {
return <View key={i} style={{ height:40, borderBottomWidth:2, borderBottomColor: '#ededed' }}><Text>{ a }</Text></View>
})
return (
<View style={styles.container}>
<Text>First</Text>
{ Arr }
<Text>Second</Text>
<TouchableHighlight style={ styles.button } onPress={ () => this._onPressOut() }>
<Text>Push</Text>
</TouchableHighlight>
</View>
);
}
});

var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:60
},
button: {
height:60,
backgroundColor: '#ededed',
marginTop:10,
justifyContent: 'center',
alignItems: 'center'
}
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);


I've set up a working example here.


[#63274] Tuesday, February 16, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jacie

Total Points: 490
Total Questions: 111
Total Answers: 105

Location: Mali
Member since Sat, Feb 12, 2022
2 Years ago
;