Search code examples
javascriptreactjsbuttonnativeonpress

How to return value from function call by button onpress?


I'm new to javascript family and I am writing a small program in react native. I am trying to SampleFunction2 to return census and render it on Flatlist when button onpress happens. Am I not supposed to return value for button onpress(event)? What is the correct approach? Thank you

    import React, { Component } from 'react';
    import { StyleSheet, FlatList,TouchableOpacity,Text, ListView,View, 
    Button, Alert } from 'react-native';
    export default class App extends Component<{}> {   

    SampleFunction2(){
     var census = [
                {name: 'Devin', id :0},
                {name:  'Jackson', id:1},
                {name:  'James', id:2},]


     return census;
   }

   render() {
    return (
      <View style={styles.container}>
      <Button onPress={this.SampleFunction2.bind(this)} title="Click here 
      to call function - One"
        //Here I was thinking I could overlay the return value into Flatlist
       />

      //<FlatList
      //<Button onPress={this.SampleFunction1.bind(this)} title= "Click 
        // here to call Function - One"/>
        //data = {this.SampleFunction2()}
       // renderItem = {({item}) =>
      //<Text>{item.id}</Text>,
       // <Text>{item.name}</Text>
     // }

     // />


      </View>
    );
  }

Solution

  • You dont actually return value from onPress, but you can set data to component state and show it if available. Following should work.

    export default class App extends Component {   
      constructor() {
        this.state = {}
      }
      SampleFunction2(){
         this.setState({census: [
                {name: 'Devin', id :0},
                {name:  'Jackson', id:1},
                {name:  'James', id:2}]})
     }
     render() {
       const census = this.state.census;
       return (
         <View style={styles.container}>
           <Button onPress={this.SampleFunction2.bind(this)} title="Click here to call function - One" />
    
         {!census ? "" : (<FlatList data={census} renderItem={({item}) => <Text>{item.name}</Text>} />)}
         </View>
       );
     }