Eduardo
Eduardo

Reputation: 1831

React Native - Call method from a function passed as prop

I am working with a library called react-native-linkedin, this library gives an option to override a method called renderButton(), to create the button which triggers login process.

Now I need to call a method open inside class LinkedInModal, this class is the same that receives renderButton as prop.

How can I call this "open" method from my renderButton method?, I have tried:

LinkedInModal.open()

Method looks like:

renderButton = () => {
        return (React.createElement(TouchableOpacity, 
                  { accessibilityComponentType: 'button', accessibilityTraits: ['button'], 
                    onPress: LinkedInModal.open() 
                  },
                React.createElement(Text, {style: {color: "#FFF"}}, "Continue with Linkedin")));
    }

And it is passed to the component as:

<LinkedInModal
                        clientID="..."
                        clientSecret="..."
                        redirectUri="https://www.linkedin.com/developer/apps"
                        onSuccess={token => this.linkedinLogin(token.access_token)}
                        linkText="Continue with Linkedin"
                        renderButton={this.renderButton}
                    />

But it does not work.

Error I get is:

    TypeError: _reactNativeLinkedin.default.open is not a function. 
(In '_reactNativeLinkedin.default.open()', '_reactNativeLinkedin.default.open' is undefined)

Upvotes: 0

Views: 397

Answers (2)

Eduardo
Eduardo

Reputation: 1831

Solution is to create a reference:

linkedRef = React.createRef();

then when calling the component, pass it as prop:

            <LinkedInModal
                ref={this.linkedRef}
                clientID="..."
                clientSecret="..."
                redirectUri="https://www.linkedin.com/developer/apps"
                onSuccess={token => this.linkedinLogin(token.access_token)}
                linkText="Continue with Linkedin"
                renderButton={this.renderButton}
            />

And in my custom method use it:

onPress={() => this.linkedRef.current.open()}>

Upvotes: 1

Custodio
Custodio

Reputation: 8934

It seems that you are not wrapping the Text correctly. Can you try:

renderButton = () => (
  <TouchableOpacity 
      accessibilityComponentType="button" 
      accessibilityTraits={['button']}
      onPress={() => LinkedInModal.open()}>
    <Text style={{color: "#FFF"}}> Continue with Linkedin </Text>
  </TouchableOpacity>
)

Upvotes: 0

Related Questions