I'd like the user to be able to grab a link from a comment (string), similar to link.
Is there a simple way to do this?
I believe it is addressed here (https://github.com/facebook/react-native/issues/3148),
But I'm not quite sure how to implement it.
Thank you.
You can use react-native-hyperlink:
import Hyperlink from 'react-native-hyperlink'
import {Text, Linking} from 'react-native'
const MyComponent = () => (
<Hyperlink onPress={Linking.openURL}>
<Text>{"Click on https://stackoverflow.com to test"}</Text>
</Hyperlink>
)
I made a quick demo based on the component that was in the link.
I couldn't test LinkingIOS in that environment but these docs should get you there.
Here's the raw source:
var HyperText = React.createClass({
render: function() {
// Check if nested content is a plain string
if (typeof this.props.children === 'string') {
// Split the content on space characters
var words = this.props.children.split(/\s/);
// Loop through the words
var contents = words.map(function(word, i) {
// Space if the word isn't the very last in the set, thus not requiring a space after it
var separator = i < (words.length - 1) ? ' ' : '';
// The word is a URL, return the URL wrapped in a custom <Link> component
if (word.match(/^https?\:\//)) {
return <Link key={i} url={word}>{word}{separator}</Link>;
// The word is not a URL, return the word as-is
} else {
return word + separator;
}
});
// The nested content was something else than a plain string
// Return the original content wrapped in a <Text> component
} else {
console.log('Attempted to use <HyperText> with nested components. ' +
'This component only supports plain text children.');
return <Text>{this.props.children}</Text>;
}
// Return the modified content wrapped in a <Text> component
return (
<Text>
{contents}
</Text>
);
}
});
var Link = React.createClass({
render: function() {
return <Text onPress={this.openUrl.bind(this, this.props.url)}>{this.props.children}</Text>;
},
openUrl: function(url) {
LinkingIOS.canOpenURL(url, (supported) => {
if (!supported) {
AlertIOS.alert('Can\'t handle url: ' + url);
} else {
LinkingIOS.openURL(url);
}
});
}
});
Hope this somewhat helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With