Reputation: 14425
I am doing:
import React from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, Linking } from 'react-native';
/**
* Used to create external link to other websites
*/
class ExternalLink extends React.Component {
_openLink = async () => {
const { href } = this.props;
if (await Linking.canOpenURL(href)) {
await Linking.openURL(href);
}
};
render() {
const { href, children, ...rest } = this.props;
return (
<TouchableOpacity
accessibilityRole="link"
onPress={this._openLink} // eslint-disable-line no-underscore-dangle
href={href}
{...rest}
>
{children}
</TouchableOpacity>
);
}
}
ExternalLink.propTypes = {
/** External URL */
href: PropTypes.string.isRequired,
/** Any node */
children: PropTypes.node.isRequired,
};
export default ExternalLink;
However, this open in current tab, is there a way to open the URL in a new tab?
Upvotes: 9
Views: 10349
Reputation: 534
I guess there are two primary options:
You can use only the window.open() function in the web:
if(Platform.OS == 'web'){
window.open(url, '_blank');
} else {
Linking... // normal Linking react-native
}
Or you can create a custom Linking from the react-native-web (https://github.com/necolas/react-native-web/blob/master/packages/react-native-web/src/exports/Linking/index.js):
CustomLinking.js :
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import invariant from 'fbjs/lib/invariant';
const initialURL = canUseDOM ? window.location.href : '';
const CustomLinking = {
addEventListener() {},
removeEventListener() {},
canOpenURL(): Promise<boolean> {
return Promise.resolve(true);
},
getInitialURL(): Promise<string> {
return Promise.resolve(initialURL);
},
openURL(url: string, target = '_self'): Promise<Object | void> {
try {
open(url, target);
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
}
},
_validateURL(url: string) {
invariant(typeof url === 'string', 'Invalid URL: should be a string. Was: ' + url);
invariant(url, 'Invalid URL: cannot be empty');
}
};
const open = (url, target) => {
if (canUseDOM) {
window.open(
url,
target // <- This is what makes it open in a new window.
);
}
};
export default CustomLinking;
Usage:
import Linking from "./CustomLinking";
Linking.openURL(href, '_blank');
Upvotes: 19