Rendering html tags from MongoDB in React component

I’m sure this is super simple, and maybe I’m just searching for the wrong terminology (newbie here), but if I have the following text stored in a document in a collection :

some text here <img src="http://somewhere.com/someimage.jpg" /> some more text here

How do I render that html tag to the browser (displaying the actual image) in a components output - instead of just printing the text?

This is what I’ve attempted using Fragment (not sure that this is even the correct thing to be using) but it throws errors :

convertToFragment(e) {
    return (
      <Fragment>
        {e}
      </Fragment>
    )
 }

And this is in my render :

render() {
    return (
      <div className="chat" ref={el => { this.el = el; }}>
        <ul>
          <li className="chat-username">{this.props.username}</li>
          <li className="chat-message">{this.convertToFragment(this.props.message)}</li>
        </ul>
      </div>
    );
}

And the error :

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

Also tried it directly in the render method :

render() {
    return (
      <div className="chat" ref={el => { this.el = el; }}>
        <ul>
          <li className="chat-username">{this.props.username}</li>
          <li className="chat-message">
              <Fragment>{this.props.message)</Fragment>
          </li>
        </ul>
      </div>
    );
}

But getting the exact same error.

Found a way to do it, not over the moon about this though, it’s a security nightmare.

Gonna spend some time to see if I can lock this down with some server side business, but here it is…

function createMarkup() {
  return {__html: 'First &middot; Second'};
}
function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

Found this excellent solution on my travels, works very similarly to PHP’s strip_tags() function.
Also allows you to whitelist certain tags which is exactly what I need in my situation.

stripTags(input, allowed) {
    allowed = (((allowed || '') + '')
    .toLowerCase()
    .match(/<[a-z][a-z0-9]*>/g) || [])
    .join('');
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
    commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '')
    .replace(tags, function($0, $1) {
      return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
  }

Useage (contentToStripGoesHere, 'whitelist of allowed tags here')

Example :

stripTags(content, '<img><b><i>');

1 Like