vemund
vemund

Reputation: 1807

Do stuff in a component that renders a flatlist

I have a Post component that I use to render posts in a FlatList. Right now the component is only rendering text and images to the Flatlist, but in the Post component, there are buttons that should do things like deleting, opening a new screen etc. based on the functions which are again based on the information from the specified item in the FlatList that is clicked.

A part of my app.js

  deletePost = (author) => {
    alert("Deleted post by" + author)
  }
  renderItem = ({ item, index }) => {
    return (
      <Post
        author={item.user}
      />
    )
  }
  render() {
    return (
     <FlatList data={this.state.getData} renderItem={this.renderItem}>
     </FlatList>
    )
  }

This is the component

const Post = (props) => {
  return (   
          <Text onPress={() => props.delete(props.author)}>
            <Icon />
          </Text>
  )
}

This is where I am stuck. I get the alert, but the author is rendered as undefined.

Upvotes: 1

Views: 36

Answers (2)

Papi
Papi

Reputation: 769

Answering the question specified in the comment, you should pass the arg to the function, like:

deletePost = (author) => {
  alert("Deleted post by" + author)
}

Upvotes: 1

crystal_17
crystal_17

Reputation: 737

Hope it would help you. Please try it as following:

renderItem = ({ item, index }) => {
  return (
    <Post
      author={item.user}
      delete={this.deletePost}
    />
  )
}

Also deletePost method should be as below.

deletePost = (author) => {
  alert("Deleted post by" + author)
}

Upvotes: 1

Related Questions