0

Hi i'm new to React native and trying render components by calling a function inside render but it doesn't seem to work.

my function:

renderData = () => {
    this.state.data.map(x => {
      return (
         <View>
           <Text> {x.data.title} </Text>
         </View>
       )
    });
  };

Works if i do this:

  render() {

    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.text}>Enter Username</Text>
        {this.state.data.map(x => {
          return <Text style={styles.bodyText}> {x.data.title} </Text>;
        })}
      </SafeAreaView>
    );
  }
}

But not this:

  render() {

    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.text}>Enter Username</Text>
        {this.renderData()}
      </SafeAreaView>
    );
   }
  }

I'm lost as to why it doesn't work with the second code

1 Answer 1

2

That's because you aren't returning anything from renderData to actually render. Add a return statement:

return this.state.data.map(x => {
  return (
     <View>
       <Text> {x.data.title} </Text>
     </View>
   )
});

You actually have to return the new mapped elements so that when you call it in {this.renderData()} you get the new elements. Or else you're doing {undefined} since you currently have no return value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.