Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Using Hooks in Flatlist

I am trying to render a FlatList:

  <FlatList
    removeClippedSubviews
    numColumns={1}
    {...{ data }}
    extraData={this.state}
    renderItem={object => renderItem(object)}
  />

It, of course, works fine with the below function.

function renderItem(object) {
  return <Text>Test</Text>;
}

However, when adding React Hooks, such that:

function renderItem(object) {
  const [foo, setFoo] = useState("bar");
  return <Text>{foo}</Text>;
}

RN returns:

Hooks can only be called inside the body of a function component.

Hooks work elsewhere in the codebase, so it's not a package mismatch issue. Any help greatly appreciated.

like image 553
o1n3n21 Avatar asked Mar 20 '19 09:03

o1n3n21


1 Answers

You cannot call hooks inside functional component. You can instead convert functions to functional components

  <FlatList
    removeClippedSubviews
    numColumns={1}
    {...{ data }}
    extraData={this.state}
    renderItem={object => <TextComponent item={object} />}
  />


function TextComponent ({item}) {
  const [foo, setFoo] = useState("bar");
  return <Text>{foo}</Text>;
}
like image 176
Shubham Khatri Avatar answered Sep 21 '22 20:09

Shubham Khatri