Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading