showtime
showtime

Reputation: 1462

Can I call props.navigation in Flatlist data?

I have a const declared which has parameters passed from another page.

const obj = this.props.navigation.state.params.item;
const itemArray = Object.values(obj.name)

Now, i am calling itemArray in Flatlist data, see below.

Here is my Flatlist:

 <FlatList
      key={this.keyExtractor}
      data={itemArray}
      renderItem={({item}) => this.renderText(item)}
    />

The problem is that its not displaying the text. Its just blank.

Here is the render method I am calling in Flatlist:

renderText = (itt) => {

    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <ListItem 
        title={itt.name}
        />
      </View>
    )
  }

Upvotes: 1

Views: 301

Answers (4)

Andrew
Andrew

Reputation: 28539

You should be able to use the FlatList.

Here is how I would implement it in the render method of your component.

  1. Notice that you don't need to use this infront of the obj variable.
  2. Also you have spelt item wrong in your renderItem function, that may cause you problems if you don't correct it.
  3. The object that you are passing, for this specific code to work, should be an array of strings, something like ['first', 'second', 'third']
  4. Also you should have defined a function as a keyExtractor inside your component.

keyExtractor = (item, index) => {
  return index.toString();
}

render () {
  const obj = this.props.navigation.state.params.item;
  return (
   <FlatList
     key={this.keyExtractor}
     data={obj}
     renderItem={({ item }) => <Text>{item}</Text>}
   />
  );
}

Upvotes: 1

user8603159
user8603159

Reputation:

Since FlatList doesn't accept an object you have to do a workaround. You have to also create an array and push your object there.

const obj = this.props.navigation.state.params.item;
    var propsArray = [];
    const itemArray = Object.assign(obj)
    propsArray.push(itemArray)

    return (
      <View>
        <FlatList
          key={this.keyExtractor}
          data={propsArray}
          renderItem={({ item }) => this.renderText(item)}
        />
      </View>
}

and your render method should remain the same:

renderText = (itt) => {

    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <ListItem 
        title={itt.name}
        />
      </View>
    )
  }

Upvotes: 1

Vaibhav Bavishi
Vaibhav Bavishi

Reputation: 121

try this

renderText = (itt) => {
    return (
      <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
        <ListItem 
        title={itt}
        />
      </View>
    )
  }

Upvotes: 0

Maneesh
Maneesh

Reputation: 674

You can directly use

<FlatList
      key={this.keyExtractor}
      data={this.props.navigation.state.params.item}
      renderItem={({ iteemm }) => <Text>{iteemm}</Text>}
/>

Upvotes: 0

Related Questions