Created
October 18, 2018 09:57
-
-
Save cyrilf/64f2f271c7968a4090d143608bfd59d7 to your computer and use it in GitHub Desktop.
React util function to find and replace string with links in a label
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
const flattenArray = (arr) => arr.reduce((result, value) => result.concat(value), []) |
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
// const termsLabel = "By checking this box you agree to our terms" | |
// | |
// const links = [ | |
// { href: "https://something.com", title: "By checking" }, | |
// { href: "https://somewhere.com", title: "this box" }, | |
// ] | |
// | |
// const { label, unmatched } = getLabelWithLinks(termsLabel, links) | |
// | |
// `label` will be something like: | |
// `<span>["", <a href="https://something.com">By checking</a>, " ", <a href="https://somewhere.com">this box</a>, " you agree to our terms", ""]</span>` | |
const getLabelWithLinks = (label, links) => { | |
const [matched, unmatched] = links.reduce((result, link) => { | |
result[label.indexOf(link.title) !== -1) ? 0 : 1].push(link) | |
return result | |
}, [[], []]) | |
if (!matched.length) { | |
return { label, unmatched } | |
} | |
let labelResult = matched.reduce((result, link) => { | |
result = result.map(part => { | |
// if it's not a string OR it is but doesn't contain the link title | |
if (typeof part !== "string" || part.indexOf(link.title) === -1) { | |
return part | |
} | |
// split on the title (return an array of [beforeTitle, afterTitle]), and then insert the link in the middle | |
part = part.split(link.title) | |
return [part[0], <Link key={`${link.title}-${link.href}`} link={link}>{link.title}</Link>, part[1]] | |
}) | |
return flattenArray(result) | |
}, [label]) | |
labelResult = <span>{labelResult}</span> | |
return { label: labelResult, unmatched } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment