Search code examples
react-nativeopenurl

Opening website in browser on button press


I am fairly new to react-native (started working with it two days ago) and therefore I am not able to make any of the solutions I found online work for me. I have a screen with a few buttons and I would like to open a website in default browser when one of the buttons is pressed. However, my current solution seems to open the website already when launching the app instead of on press of the button.

Here's what I have built using snippets I found online:

Function to open URL:

const openURL = (url) => {
    Linking.openURL(url).catch((err) => console.error('An error occurred', err));
  }

Using the function:

<TouchableOpacity style={styles.box} onPress={openURL('https://www.moodplan.net/skilldesmonats')}>
    <MaterialCommunityIcons name="diamond-stone" size={100} color="white" />
    <Text style={[Styles.text16B,{color:color.white}]}>
    Please open website
    </Text>
</TouchableOpacity>`

As mentioned above, the website does now open directly when I refresh the app in my emulator instead of when clicking the button.

Many thanks for your help!


Solution

  • <TouchableOpacity style={styles.box} onPress={()=>{openURL('https://www.moodplan.net/skilldesmonats')}}>
        <MaterialCommunityIcons name="diamond-stone" size={100} color="white" />
        <Text style={[Styles.text16B,{color:color.white}]}>
        Please open website
        </Text>
    </TouchableOpacity>`
    

    Change is here

    onPress={()=>{openURL('https://www.moodplan.net/skilldesmonats')}}