Search code examples
javascriptreactjsradio-buttonmaterial-uiradio-group

Passing String with HTML entity as a prop not rendered properly in material UI


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&#39;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&#39;m male";
<FormControlLabel value={value} label={label} />
output: I&#39;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.

https://codesandbox.io/s/material-demo-543y4


Solution

  • &....; 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&#39;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&#39;m male`;
    console.log(label);