Search code examples
javascriptreact-nativefunctiontouchableopacity

Why Linking.openURL fires automaticaly without TouchableOpacity?


i have a problem with function in React Native. I checking if the String is e-mail, text or phone and returns appropriate object, e.g Linking.openURL(mailto:${phone}).

But function automatically fires the URL and forwarding me to Phone Application, what im doing wrong?

A function to check value in a String

function checkResult(result){
  let emailChecker = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if( !( emailChecker.test(result))){
    return Linking.openURL(`mailto:${result}`)
  }

  if(isNaN(result)){
    return Linking.openURL(`tel:${result}`)
  }
}

My touchableOpacity

<TouchableOpacity
        onPress={checkResult(result)}
        >
        <Text
          style={{
            color: 'blue',
            fontSize: 20,
            marginTop: 10,
            marginBottom: 40,
          }}
        >
          {result}
        </Text>
        </TouchableOpacity>

Solution

  • onPress={checkResult(result)} this will result in calling the function checkResult when you pass it to the component, so the function will execute on render.

    Update your onPress callback to () => checkResult(result).

    <TouchableOpacity
      onPress={() => checkResult(result)} 
    >
      <Text
          style={{
          color: 'blue',
          fontSize: 20,
          marginTop: 10,
          marginBottom: 40,
        }}
        >
          {result}
        </Text>
    </TouchableOpacity>
    
    

    for more details on passing function to component - here