react-format-text
Version:
Simple link and newline text formatting for react
61 lines (48 loc) • 1.5 kB
JavaScript
var React = require('react');
var PropTypes = require('prop-types');
var createReactClass = require('create-react-class');
var linkify = require('linkify-it')();
var tlds = require('tlds');
linkify.tlds(tlds);
var format = function format(str, options) {
var matches = linkify.match(str) || [];
var index = 0;
var elements = [];
var newlines = function newlines(str, i) {
var parts = str.split(/\n|\r/);
parts.forEach(function (part, j) {
if (part) elements.push(part);
if (j < parts.length - 1) elements.push(React.createElement('br', { key: i + '.' + j }));
});
};
matches.forEach(function (match, i) {
var part = str.slice(index, match.index);
var target = 'target' in options ? options.target : /^http(s)?:/.test(match.url) ? '_blank' : null;
var rel = 'rel' in options ? options.rel : target === '_blank' ? 'noopener noreferrer' : null;
index = match.lastIndex;
newlines(part, i);
elements.push(React.createElement(
'a',
{ key: i, target: target, rel: rel, href: match.url },
match.text
));
});
newlines(str.slice(index), matches.length);
return elements;
};
module.exports = createReactClass({
propTypes: {
children: PropTypes.string,
target: PropTypes.string,
rel: PropTypes.string
},
render: function render() {
var text = this.props.children;
return React.createElement(
'span',
null,
text && format(text, this.props)
);
}
});
;