Search code examples
reactjsreact-hookshtml-parsingsanitization

How can i pass HTML inside React Hook Function and display inside my component secure?


I have a custom react hook to display a popover when i hover over an nav item like this:

<a 
  href={url} 
  onMouseEnter={(e) => showPopover(e.target)} 
  onMouseLeave={() => showPopover(false)}

> Hover me </a>

I want to pass the content to the hook and display inside my popover. If I only had text this would be pretty simple, however the popover can also contain JSX, like an icon component or HTML tags like <div> or <p>

So what is the best way to pass the content to my hook. Could it work like that?

<a 
  href={url} 
  onMouseEnter={(e) => showPopover(e.target, "<div>This is a div</div>")} 
  onMouseLeave={() => showPopover(false)}

> Hover me </a>

I pass the HTML String to my hook and parse them via a library like react-html-parser However, I then have the problem that i also need sanitized my HTML. Would there also be a possibility to pass only the text and handle the styling somehow differently?


Solution

  • You are trying to transfer something that you should not, normally. If you want to display an HTML with CSS, then this should go into a component.

    Pass into that component the argument that you need to choose whatever style/icon you want to display and render the component.

    if (shouldComponentARender){
        render(ComponentA)
    }else if(shouldComponentBRender){
        render(ComponentB)
    }
    

    Here, you can easily pass only a string or flag. That would be better testable and extendable.