'dangerouslySetInnerHTML returns [object, object] with any input that contains markup (eg 'a', 'div', 'span', etc)

I've created a custom component that is used simply for display purposes:

import React from 'react';
import './CardContainer.css';
import sanitizeHtml from 'sanitize-html';

interface ContainerProps {
    content?: any,
    children?: any;
}

const CardContainer: React.FC<ContainerProps> = ({ content = "n/a", children }) => {
    
    //children override content if populated for backwards compatibility
    let sanitise = "";
    children ? sanitise = children : sanitise = content;

    const clean = sanitizeHtml(sanitise, {
        allowedTags: ['b', 'i', 'em', 'strong', 'a', 'div', 'span', 'svg', 'IonIcon', 'icon', 'ion-icon'],
        allowedAttributes: {
          a: ['href', 'target'],
          div: ['class', 'className'],
          span: ['style', 'class', 'className']
        }
    });



  return <><div color={colour} dangerouslySetInnerHTML={{__html: clean}}/><div>clean</div></>
};

export default CardContainer;

If I send plain text into it, there is no problem. But if the content or children contains any sort of html tags, the content of those tags is returned as [object, object].

I've done some testing and it seems that if content or children are passed through sanitizeHtml or dangerouslySetInnerHTML this is always the result.

So for example the following is what I get if I play around with the return statement in my Cardcontainer.

The following always result in [object, object]

return <div color={colour} dangerouslySetInnerHTML={{__html: clean}}/>
return <div color={colour} dangerouslySetInnerHTML={{__html: children}}/>
return <div color={colour} dangerouslySetInnerHTML={{__html: sanitize}}/>

return <div>clean</div>
return <div>sanitize</div>

However, the following renders as expected.

return <div>children</div>

I'm evidently missing something here, but I'm totally confused at this point as it seems both sanitizeHtml and dangerouslySetInnerHTML are having the same impact on the the passed in content regardless of whether it's done as a variable or as children.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source