Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React - replace string by render or component
const replaceStrByRender = (
str: string,
substr: string | RegExp,
render: (part: string, i: number) => JSX.Element
) => {
if (!str || !substr) return str
const parts = str.split(substr)
const results: Array<string | JSX.Element | null> = []
let index = 0
for (let i = 0; i < parts.length; i++) {
if (parts[i]) results.push(parts[i])
if (i + 1 < parts.length) {
const rendered = render(parts[i], index++)
if (rendered) results.push(rendered)
}
}
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment