In react native i\'m trying to dynamically add an element to the DOM on a button click.
This is what I have so far in the Render() method:
A good way to do this is to set up an array and then map through the array in the view. To add an element, push an item to the array and reset the state of the array:
getInitialState(){
return { rows: [] }
},
_addRow(){
this.state.rows.push(index++)
this.setState({ rows: this.state.rows })
}
let rows = this.state.rows.map((r, i) => {
return
Row { r }, Index { i }
})
And use the variable like this:
{ rows }
I've set up a working example of this here, and pasted the code below as well.
https://rnplay.org/apps/-ENWEw
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} = React;
let index = 0
var SampleApp = React.createClass({
getInitialState(){
return { rows: [] }
},
_addRow(){
this.state.rows.push(index++)
this.setState({ rows: this.state.rows })
},
render() {
let CheckIndex = i => {
if((i % 2) == 0) {
return styles.gray
}
}
let rows = this.state.rows.map((r, i) => {
return
Row { r }, Index { i }
})
return (
Add new row
{ rows }
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 60,
},
gray: {
backgroundColor: '#efefef'
},
row: {
height:40,
alignItems: 'center',
justifyContent: 'center',
borderBottomColor: '#ededed',
borderBottomWidth: 1
},
button: {
alignItems: 'center',
justifyContent: 'center',
height:55,
backgroundColor: '#ededed',
marginBottom:10
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);