React/Next js contentEditable Security with onBlur

33 Views Asked by At

I'm working on a feature in a React application that involves a contentEditable div. The goal is to allow text editing while preserving some user HTML styling. I'm currently sanitizing the contents of the div on the onBlur event and not on onInput or onChange. My question is whether this approach is secure enough.

Here is the implementation using useState:

const [content, setContent] = useState("")

const onContentBlur = useCallback(evt => {
  setContent(sanitizeContent(evt.currentTarget.innerHTML))
}, [])

return (
  <div
    css={scrollBar}
    contentEditable={!helpers.loading}
    onBlur={onContentBlur}
    dangerouslySetInnerHTML={{__html: content}}
  />
)

This content is being parsed, edited, and stored on a server when a user clicks another button on the page.

I am also considering an alternative approach using useRef, which seems to work fine for my application. Here is that implementation:

const contentRef = useRef();

const onContentBlur = useCallback(evt => {
  const content = sanitizeContent(contentRef.current.innerHTML)
  contentRef.current.innerHTML = content
}, [])

return (
  <div
    css={scrollBar}
    contentEditable={!helpers.loading}
    onBlur={onContentBlur}
    ref={contentRef}
  />
)

Is sanitizing on the onBlur event sufficiently secure for preventing issues like XSS attacks?

Between using useState with dangerouslySetInnerHTML and useRef for direct DOM manipulation, which approach is more secure and recommended?

Are there any best practices or additional considerations I should be aware of for this kind of functionality in React?

Any insights or experiences with similar implementations would be greatly appreciated!

0

There are 0 best solutions below