I came across an issue with the radio buttons in material UI. Material UI is currently accepting value as a prop for the FormControlLabel component. When we pass a string with an HTML entity as shown below, it is parsed as expected.
<FormControlLabel value="female" label="I'm male" />
output: I'm male
When we pass the same string as a prop, it is not being parsed correctly and the special character is being shown as it was sent.
const label="I'm male";
<FormControlLabel value={value} label={label} />
output: I'm male
I tried to search this online, but couldn't find any relevant threads. Please link me to the issue if it exists already or please provide an alternative solution if anyone has a solution to it. Below is the codesandbox link.
&....;
is a HTML Entitiy - which is why it works when used directly in HTML and not in javascript
You need to decode it to use it in javascript
One way is as done here https://medium.com/@tertiumnon/js-how-to-decode-html-entities-8ea807a140e5
function decodeHTMLEntities(text) {
var textArea = document.createElement('textarea');
textArea.innerHTML = text;
return textArea.value;
}
So you would use it like
const label=decodeHTMLEntities("I'm male");
A far neater way in modern javascript would be to use tagged templates
const entityDecode = (() => {
const el = document.createElement('textarea');
return (strings) => {
el.innerHTML = strings.join('');
return el.value;
}
})();
const label=entityDecode`I'm male`;
console.log(label);