Skip to content

Instantly share code, notes, and snippets.

@hypervillain
Last active October 5, 2018 16:27
Show Gist options
  • Save hypervillain/db08b9297be5b556240b8f1f0363e33d to your computer and use it in GitHub Desktop.
Save hypervillain/db08b9297be5b556240b8f1f0363e33d to your computer and use it in GitHub Desktop.
Linkify DraftTail Editor using decorators
// If you're using https://github.com/lokiuz/redraft,
// reuse these methods in your renderers module.
const urlRegex = (/((?:https?(?::\/\/))(?:www\.)?(?:[a-zA-Z\d-_.]+(?:\.[a-zA-Z\d]{2,})|localhost)(?:(?:[-a-zA-Z\d:%_+.~#!?&//=@]*)(?:[,](?![\s]))*)*)/g);
function findWithRegex(regex, contentBlock, callback) {
const text = contentBlock.getText();
let matchArr;
let start;
matchArr = regex.exec(text);
while (matchArr !== null) {
start = matchArr.index;
callback(start, start + matchArr[0].length);
matchArr = regex.exec(text);
}
}
// contentState available as last argument
function handleLinkStrategy(contentBlock, callback) {
findWithRegex(urlRegex, contentBlock, callback);
}
const DraftLink = ({ decoratedText, children }) => (
<a
className="link-classname"
href={decoratedText}
rel="noopener noreferrer"
style={{ color: 'blue' }}
target="_blank"
title={`link to ${decoratedText}`}
>
{children}
</a>
);
const Editor = (props) => {
const {
...rest
} = props;
return (
<DraftailEditor
{...rest}
decorators={[{
strategy: handleLinkStrategy,
component: DraftLink,
}]}
/>
);
};
export default Editor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment