JSFiddle - React, Tailwind, and code Playground
by alexb
HTML
<div id="app"></div>
React
let id = 0;
const contact = (name, email) => ({ id: id++, name, email });
const contacts = [
contact('Alex Barrett', '[email protected]'),
contact('Jules-Pierre Mao', '[email protected]'),
contact('Esteban Sorrento-Gillis', '[email protected]'),
contact('Chrisjen Avasarala', '[email protected]'),
contact('Fred Johnson', '[email protected]'),
contact('James Holden', '[email protected]'),
];
const getContacts = (substr) => {
const subset = contacts.filter(x => x.name.toLowerCase().indexOf(substr.toLowerCase()) >= 0 || x.email.toLowerCase().indexOf(substr.toLowerCase()) >= 0);
let reject;
const p = new Promise(function(resolve, reject_) {
setTimeout(() => resolve(subset), 1000)
reject = reject_;
});
p.abort = () => reject();
return p;
}
function ireplace(str, substr, replaceWith) {
for (let i = 0; i <= str.length - substr.length; i++) {
for (let j = 0; j < substr.length; j++) {
if (str[i + j].toLowerCase() !== substr[j].toLowerCase()) {
break;
}
if (j === substr.length - 1) {
let newSubstr;
if (typeof replaceWith === 'function') {
newSubstr = replaceWith(str.substr(i, j + 1));
}
else {
newSubstr = replaceWith;
}
str = str.substr(0, i) + newSubstr + str.substr(i + j + 1);
i += newSubstr.length - substr.length;
}
}
}
return str;
}
const el = document.createElement('div');
const highlight = (search, text) => {
text = ireplace(text, search, x => '{MARK}' + x + '{/MARK}');
el.innerText = text;
let html = el.innerHTML;
html = ireplace(html, '{MARK}', '<mark>');
html = ireplace(html, '{/MARK}', '</mark>');
return { __html: html };
};
const Contact = props => (
<li>
<span dangerouslySetInnerHTML={highlight(props.highlight, props.name)}/><br/>
<i dangerouslySetInnerHTML={highlight(props.highlight, props.email)}/>
</li>
);
class AutocompleteInput extends React.Component {
constructor(props) {
super(props);
...