Shah Alom
Shah Alom

Reputation: 1055

HTML special character (& symbol) not rendering in React component

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?

Upvotes: 19

Views: 32302

Answers (3)

Dmitryi Iarovatyi
Dmitryi Iarovatyi

Reputation: 11

const getDecodedString = (str) => {
    const txt = document.createElement('textarea');
    txt.innerHTML = str;
    return txt.value;
};

Upvotes: 1

Denis Rybalka
Denis Rybalka

Reputation: 1871

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.

Upvotes: 6

Kyle Richardson
Kyle Richardson

Reputation: 5645

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.

Upvotes: 9

Related Questions