-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: make Linkify component reusable
Signed-off-by: Adrien Delannoy <[email protected]>
- Loading branch information
Showing
2 changed files
with
41 additions
and
34 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import LinkifyIt from 'linkify-it'; | ||
import React from 'react'; | ||
|
||
interface Props { | ||
text: string; | ||
} | ||
|
||
const linkify = new LinkifyIt(); | ||
|
||
export default function LinkifiedText({text}: Props) { | ||
const matches = linkify.match(text); | ||
|
||
if (!matches) { | ||
return <>{text}</>; | ||
} | ||
|
||
const parts = []; | ||
let lastIndex = 0; | ||
|
||
matches.forEach(match => { | ||
if (match.index > lastIndex) { | ||
parts.push(<span key={`text-${lastIndex}`}>{text.slice(lastIndex, match.index)}</span>); | ||
} | ||
parts.push( | ||
<a key={`link-${match.index}-${match.text}`} href={match.url} target='_blank' rel='noopener noreferrer' className='underline'> | ||
{match.text} | ||
</a> | ||
); | ||
lastIndex = match.lastIndex; | ||
}); | ||
|
||
if (lastIndex < text.length) { | ||
parts.push(<span key={'text-end'}>{text.slice(lastIndex)}</span>); | ||
} | ||
|
||
return <>{parts}</>; | ||
} |
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