Created
November 26, 2021 09:01
-
-
Save nhuxhr/dc8e7e4a2fd64b39b47c65353bea2503 to your computer and use it in GitHub Desktop.
AutoLink in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* AutoLink in React | |
* @author JSX Clan <jsxclan.dev@gmail.com> | |
*/ | |
function AutoLink({ text }) { | |
const delimiter = /((?:https?:\/\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\-]{1,61}[a-z0-9])?\.[^\.|\s])+[a-z\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\d{1,5})*[a-z0-9.,_\/~#&=;%+?\-\\(\\)]*)/gi; | |
return ( | |
<React.Fragment> | |
{text.split(delimiter).map(word => { | |
let match = word.match(delimiter); | |
if (match) { | |
let url = match[0]; | |
return ( | |
<a href={url.startsWith("http") ? url : `http://${url}`}>{url}</a> | |
); | |
} | |
return word; | |
})} | |
</React.Fragment> | |
); | |
} | |
ReactDOM.render( | |
<AutoLink text='foo bar baz http://example.org bar' />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment