Created
April 1, 2020 09:42
-
-
Save alexengrig/2343857a77f2c27b96438dfc4a463f82 to your computer and use it in GitHub Desktop.
React - text with links
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
import React, { memo } from 'react'; | |
import * as linkifyjs from 'linkifyjs'; | |
function splitTextAndLinks(value = '') { | |
const links = linkifyjs.find(value); | |
const values = []; | |
let index = 0; | |
for (const { value: link, href } of links) { | |
const urlBeginIndex = value.indexOf(link, index); | |
const text = value.substring(index, urlBeginIndex); | |
values.push({ text }); | |
values.push({ text: link, href }); | |
index = urlBeginIndex + link.length; | |
} | |
if (index < value.length) { | |
values.push({ text: value.substring(index) }); | |
} | |
return values; | |
} | |
function TextWithLinks({ value }) { | |
const values = splitTextAndLinks(value); | |
return ( | |
<div> | |
{values.map(({ text, href }, key) => { | |
return href | |
? <a key={key} href={href}>{text}</a> | |
: <span key={key}>{text}</span>; | |
})} | |
</div> | |
); | |
} | |
export default memo(TextWithLinks); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add linkifyjs to package.json:
npm install --no-optional linkifyjs