19

Consider this react code:

subTopicOptions = curSubTopics.map((topic) => {
    return (
        <option value={topic.id}>{topic.name}</option>
    )
});

The topic.name output Environment &amp; Forest value from rest API to display.

How can I display Environment & Forest in the select field?

Shah Alom
  • 1,031
  • 1
  • 14
  • 26
  • React escapes the topic name in order to protect you from XSS attacks. The escaped value should display correctly on the actual page, the change is made automatically to make the distinction that you want to display an "&" character and not used for something else. – Froast Dec 24 '17 at 17:16
  • Here is a [code sandbox](https://codesandbox.io/s/ww7zq93j5k) of a way to do it using `DOMParser`. – Kyle Richardson Dec 24 '17 at 17:39

3 Answers3

9

You could use the browser's native parser as described in the top answer to Decode & back to & in JavaScript.

Using the DOMParser api, you can do the following:

const strToDecode = 'Environment &amp; Forest';
const parser = new DOMParser();
const decodedString = parser.parseFromString(`<!doctype html><body>${strToDecode}`, 'text/html').body.textContent;
console.log(decodedString);

What you're doing there is using the DOMParser to create a HTMLDocument by appending our string to decode to the end of '<!doctype html><body>'. We can then access the decoded value of our string in the textContent of the body of that newly created HTMLDocument.

Kyle Richardson
  • 5,567
  • 3
  • 17
  • 40
6

If creating the topic is under your control, you can use dangerouslySetInnerHTML

subTopicOptions = curSubTopics.map((topic) => {
    return (
        <option value={topic.id} dangerouslySetInnerHTML={{__html: topic.name }} />
    )
});

You shoukd be aware that use of the innerHTML can open you up to a cross-site scripting (XSS) attack, so use it wisely.

Denis Rybalka
  • 1,821
  • 3
  • 18
  • 28
1
const getDecodedString = (str) => {
    const txt = document.createElement('textarea');
    txt.innerHTML = str;
    return txt.value;
};
  • Welcome to SO. When answering a question, please explain how the code you provided answers the question. When answering an old question with other answers, it is a good practice to explain why yours is different from or improves on the others. – rmlockerd Aug 08 '21 at 02:43