Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Dynamically Add Element to DOM on button press

Tags:

react-native

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:

<TouchableHighlight  
    style={styles.button} 
    onPress={this.addAnotherRow}>

        <Text>Add new row</Text>

</TouchableHighlight>

I'm not sure what to return from the onpress function to add another DOM element:

addAnotherRow() {
    return <Text>New Row</Text>
}

Any help please?

like image 815
samb90 Avatar asked Feb 20 '16 13:02

samb90


1 Answers

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 <View key={ i } style={[styles.row, CheckIndex(i)]}>
              <Text >Row { r }, Index { i }</Text>
           </View>
})

And use the variable like this:

<View>
  { rows }
</View>

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 <View key={ i } style={[styles.row, CheckIndex(i)]}>
                    <Text >Row { r }, Index { i }</Text>
                 </View>
    })

    return (
      <View style={styles.container}>
        <TouchableHighlight onPress={ this._addRow } style={styles.button}>
            <Text>Add new row</Text>
                </TouchableHighlight>
        { rows }
      </View>
    );
  }
});

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);
like image 141
Nader Dabit Avatar answered Nov 19 '22 02:11

Nader Dabit