Issue
I'm coding in react native and I want to open my button which goes to a website that is specified in my code. I want to open the website automatically by pressing the button or running my function. I tried using the useEffect thing in react native but it didn't work. Can someone show me how to do this.
My code so far is:
// Note the additional import of useEffect
import React, { useState, useEffect, useRef } from 'react';
import { TouchableOpacity, Button, Text, View, StyleSheet } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import Constants from 'expo-constants';
export default function App() {
const [result, setResult] = useState(null);
const _handlePressButtonAsync = async () => {
let result = await WebBrowser.openBrowserAsync('https://vitech-104517.square.site/');
setResult(result);
};
return (
<View style={styles.container}>
<Button title="Open WebBrowser" onPress={_handlePressButtonAsync} />
<Text>{result && JSON.stringify(result)}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
Solution
You can useEffect
, try this way
export default function App() {
const [result, setResult] = useState(null);
useEffect(() => {
_handlePressButtonAsync();
}, []);
const _handlePressButtonAsync = async () => {
let result = await WebBrowser.openBrowserAsync('https://vitech-104517.square.site/');
setResult(result);
};
return (
<View style={styles.container}>
<Text>Website will open automatically</Text>
<Text>{result && JSON.stringify(result)}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
Answered By - Ćukasz D. Mastalerz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.