marcus
marcus

Reputation: 77

React seems to be escaping HTML before rendering in the browser causing it to appear as code in the page

I have a React class and the render function works fine. The <li> tag and the internal <a> tag render.
However, the string of HTML returned by getListItem does not render. Instead, it shows up as code on the page, as if it had been escaped.
How do I prevent this behavior in React so I can build dynamic HTML when creating components, as in the (attempted) example below?

class ExchangeListItem extends Component {
  constructor(props) {
    super(props);
  this.state = {
    };
  }

  getListItem() {
    const retStr = '<a className="nav-link active" href="'+this.props.exchange.url+'">'+this.props.exchange.name + '</a>';
    return retStr;
  }

  render() {
    return (
      <li>
        <a href="https://wwww.google.com">Link</a>
        {this.getListItem()}
      </li>
    );
  }
}

At issue here is specifically how React renders something. If it is a string, it will escape the special characters and cause (in this case) HTML to become displayed text. The other post is only asking about how to change innerHTML. In my case, I am not attempting to change an element but trying to get React to render what I intend in the first place.

Upvotes: 2

Views: 2244

Answers (2)

Dinesh Pandiyan
Dinesh Pandiyan

Reputation: 6299

I always use react-html-parser to render html content in a component.

Import the parser

import ReactHtmlParser from 'react-html-parser';

Use it in your getListItem method as follows

getListItem() {
  const retStr = '<a className="nav-link active" href="'+this.props.exchange.url+'">'+this.props.exchange.name + '</a>';
  return ReactHtmlParser(retStr);
}

Edit:

Note that react-html-parser is to parse html string that is already stored in an variable. For the above case, where the html string is constructed in the previous line, we could just return the tag in jsx format like any react component.

Upvotes: 2

Another cleaner way of doing this in ES6 without the parser is;

import React from 'react';

class ExchangeListItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  getListItem = (exchangeUrl, exchangeName) => (
    <a className="nav-link active" href={exchangeUrl}>
      {exchangeName}
    </a>
  );

  render() {
    return (
      <li>
        <a href="https://wwww.google.com">Link</a>
        {this.getListItem(this.props.exchange.url, this.props.exchange.name)}
      </li>
    );
  }
}

Upvotes: 3

Related Questions