Utilisation of 'this' in React Js

Viewed 69

i have a classic functionnal component returning what will be rendered in JSX

function Search(){

    const loadFilms = function (){
         console.log(this)); // logs undefined
    };

    return(

            <View style= {styleAreas.view}>
                <TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
                <Button title='Search' onPress= {()=> { console.log(this);loadFilms();} } />  // logs undefined
                <FlatList    
                data={films}
                keyExtractor = {item => item.id.toString()}
                renderItem={({item}) => <FilmItem filmDesc = {item} />} 
                />
            </View>

        )
}

so i'm learning JS / React, and what i don't understand why this is undefined but when we run it since Class Search extends React.Component {}. it returns the right instance. especially that i tought that in JS ( i'm maybe over simplifying) a class is a function with pre-configured prototypes etc...

thank you for your explanations :)

2 Answers

I believe you are mistaken because your function is not extending the Component class.

A react component class would begin with the declaration as so:

class App extends Component {
    render () {
        return (
            <Text>Hello World!</Text>
        )
    }
}

Class components are functions, but your function is not extending the component class.

The reason for that is that loadFilms is a function different from your 'Class'. Therefore, it has a different this context. Since you seem to use strict mode, it's undefined. You could pass it explicitly by using the call method.

function Search(){

    const loadFilms = function (){
         console.log(this)); // logs undefined
    };

    return(

            <View style= {styleAreas.view}>
                <TextInput style= {styleAreas.textinput} placeholder='Type your movie ' />
                <Button title='Search' onPress= {()=> { console.log(this); loadFilms.call(this);} } />  // logs undefined
                <FlatList    
                data={films}
                keyExtractor = {item => item.id.toString()}
                renderItem={({item}) => <FilmItem filmDesc = {item} />} 
                />
            </View>

        )
}
Related