Ajay Sharma
Ajay Sharma

Reputation: 97

Can't create function outside render in react native 0.61.1

I just created new react native app and trying to create a function and console.log onpress of TouchableOpacity but it is giving error that functionName is not defined.

Here is my code:

import React, { Component } from 'react';
import { Text, View, ScrollView, StyleSheet, TouchableOpacity } from 'react-native';

export default class Home extends Component {


    functionName = () => {
        console.log('function called');
    }


    render() {
        return (
            <ScrollView contentContainerStyle={styles.container}>
                <TouchableOpacity onPress={functionName()}>
                    <Text> Home {sliderApi} </Text>
                </TouchableOpacity>
            </ScrollView>
        )
    }
}

But when I put functionName in render method it works fine.

Upvotes: 0

Views: 430

Answers (2)

Kishan Bharda
Kishan Bharda

Reputation: 5700

Replace

<TouchableOpacity onPress={functionName()}>

with

<TouchableOpacity onPress={this.functionName}>

or with

<TouchableOpacity onPress={() => this.functionName()}>



Just for knowledge: there is no difference between {this.functionName} and {() => this.functionName()}. The reason to use arrow function "() =>" is we are calling function with parentheses () like "this.functionName()". When we call function with parentheses () it will get called directly when the code will get executed. But when we want to call the function only when "onPress or Any event" fire of "TouchableOpacity or Any component" we have to use it with arrow function "() =>" or we just have to call it like "this.functionName".

Upvotes: 2

Anshu Kumar
Anshu Kumar

Reputation: 827

you are calling the function in onPress event in wrong way. Try replacing the following line:

<TouchableOpacity onPress={functionName()}>

with

<TouchableOpacity onPress={() => this.functionName()}>

Upvotes: 1

Related Questions