Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String as html in reactjs

I have a function which returns several lines of html, like so:

render: function() {
  var badges = user.get('achievements').badges.map(function(badge) {
    var str = '<h3><span className="fa fa-fw '

    switch(badge.id) {
    case '0':
      str += ('fa-briefcase"></span><small>' + badge.text + '</small></h3>')
      break;
    case '1':
      str += ('fa-shopping-cart"></span><small>' + badge.text + '</small></h3>')
      break;
    ...
    }

    return str;
  });

  return (
    <div className="pull-right">
      {badges}
    </div>
  );
}

On doing this the string is rendered as it is on the page, as text:

<h3><span className="fa fa-fw fa-briefcase"></span><small>Visionary</small></h3><h3><span className="fa fa-fw fa-shopping-cart"></span><small>Active</small></h3><h3><span className="fa fa-fw fa-sitemap"></span><small>Lorem</small></h3><h3><span className="fa fa-fw fa-tasks"></span><small>Ipsum</small></h3><h3><span className="fa fa-fw fa-signal"></span><small>Dolor</small></h3><h3><span className="fa fa-fw fa-check-square"></span><small>Amet;</small></h3>

How do I render it as proper HTML ?

like image 356
myusuf Avatar asked May 12 '14 07:05

myusuf


1 Answers

While using dangerouslySetInnerHTML does work, I recommend avoiding it in this case since you are in control of the markup. That attribute starts with dangerously for a reason: those badges are now a vector for code injection.

render() {
    const BADGE_ID_TO_ICON_CLASS_NAME = {
      '0': 'fa-briefcase',
      '1': 'fa-shopping-cart',
      ...
    };

    return (
      <div className="pull-right">
        {user.get('achievements').badges.map(badge => (
          <h3 key={badge.id}>
            <span
              className={`fa fa-fw ${BADGE_ID_TO_ICON_CLASS_NAME[badge.id]}`}
            />
            <small>{badge.text}</small>
          </h3>
        ))}
      </div>
    );
}
like image 130
Ross Allen Avatar answered Sep 20 '22 17:09

Ross Allen