skip to Main Content

I’m coding in react native and I want to create a way for my code to automatically click on a button once the app is opened by user. I want the button to be clicked by the app automatically without the user having to click on the button themselves. My code so far is:

import React, { useRef } from 'react';
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View,Button } from 'react-native';
import {openBrowserAsync} from 'expo-web-browser'


export default function App() {
  const btnRef = useRef();

  return (
    <View style={styles.container}>
        
      
      <Button title="Open Browser" onPress={() => openBrowserAsync("https://dicateeu.co.uk")}  />
      
      <StatusBar style="auto" />
    </View>
  );
}

My code so far just opens a web browser but I want the app to open the web browser by itself.

2

Answers


  1. Use useEffect-Hook. It will execute when the screen renders.

    import React, { useEffect } from 'react';  
    
    useEffect(() => {
              openBrowserAsync('https://dicateeu.co.uk');
    }, []);
    
    Login or Signup to reply.
  2. you can use the useEffect hook to trigger the button’s onPress function after the component has been mounted

    useEffect(() => {
        if (btnRef.current) {
          btnRef.current.props.onPress();
        }
      }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search