React Native call function outside of App. Flatlist access onPress function

There is example https://reactnative.dev/docs/flatlist
Let’s say I want to add button in each flatlist item. All happens inside App.js

const Item = ({ item,.....}) => (
  <TouchableOpacity onPress={onPress} style={..}>
    <Button title='Go' onPress={() => myFunc('abc')} /> </TouchableOpacity>);

const App = () => {
 function myFunc(x){
 }
}

I get " ReferenceError: Can’t find variable: myFunc "
I solved this by moving Item inside of const App = () => { but I think it might be wrong.

Tell me please, what is the correct way?

>Solution :

You could do something like this:

const App = () => {
    
const myFunc = (args) => {
  // perform your action here.
}
    
return (
  <FlatList
    data={[{ title: 'Title Text', key: 'item1' }]}
    renderItem={({ item, index, separators }) => (
        <TouchableOpacity
          key={item.key}
          onPress={() => myFunc('abc')}
        >
          <View style={{ backgroundColor: 'white' }}>
            <Text>{item.title}</Text>
          </View>
        </TouchableOpacity>
    )}
   />
  )
}

export default App;

Also you do not need to using TouchableOpacity if you are using Button Component already.

And since you are using separate component to render item for FlatList so it can be done as below:

// Considering App as Parent Component
const App = () => {

// Considering Item as separate Component

const Item = ({item, index, separators}) => {
 return (
    <TouchableOpacity
      key={item.key}
      onPress={() => myFunc('abc')}
    >
      <View style={{ backgroundColor: 'white' }}>
        <Text>{item.title}</Text>
      </View>
    </TouchableOpacity>
  )
}
        
const myFunc = (args) => {
 // perform your action here.
}
        
return (
  <FlatList
    data={[{ title: 'Title Text', key: 'item1' }]}
    renderItem={Item}
  />
 )
}
export default App;

All code are inside App Component;

Leave a Reply