Say I have a ReactNode post:
const Post = (props:{content:string}) => {
return(
<div>
{textProcessor(props.content)}
</div>
)
}
the role of textProcessor is to 1. to sanitize the text, and 2. to identify links and inject html to highlight them.
const textProcessor = (content:string) : React.ReactNode =>{
let sanitized : string = sanitizeHTML(content);
const urlRegex : RegExp = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g
const urls : RegExpMatchArray | null = sanitized.match(urlRegex);
urls?.forEach(url=>{
sanitized = sanitized.replaceAll(url, `<a href='${url}' target='_blank'>${url}</a>`)
})
return <div className='formatted-content' dangerouslySetInnerHTML={{__html: sanitized}} />;
}
This "works" but it feels very imperative which is probably an anti-pattern when it comes to React. It also feels unsafe given that I am injecting html (I do sanitize beforehand, but feels like the React way is intended to be different). Is there another way of doing this which is more "React"?