Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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?

like image 811
Shah Alom Avatar asked Dec 24 '17 17:12

Shah Alom


People also ask

Are Special Characters allowed in HTML?

In HTML, special characters are typically those that can't be easily typed into a keyboard or may cause display issues if typed or pasted into a web page. If you plan to use any of the special characters on this page, you should use either the HTML entity name or the HTML entity number.

What are Special Characters called in HTML?

Characters with special meaning in HTML are called reserved characters.

What is HTML Special Characters PHP?

htmlspecialchars() Function: The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities. Syntax: string htmlspecialchars( $string, $flags, $encoding, $double_encode ) Parameter value: $string: This parameter is used to hold the input string.

What does special character mean in HTML?

Special characters are specific pieces of HTML code designed to display characters that are used in the HTML code or to include characters that are not found on the keyboard in the text the viewer sees.


1 Answers

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.

like image 112
Kyle Richardson Avatar answered Sep 28 '22 08:09

Kyle Richardson