Issue with rendering HTML entities in Material UI when passing as props

Encountered a problem with the radio buttons in Material UI. Currently, Material UI accepts value as a prop for the FormControlLabel component. When passing a string with an HTML entity like below, it gets parsed correctly.

<FormControlLabel value="female" label="I&#39;m male" />
output: I'm male

However, when passing the same string as a prop, it does not get parsed correctly and the special character is displayed as sent.

const label="I&#39;m male";
<FormControlLabel value={value} label={label} />
output: I&#39;m male

I searched online for relevant threads but couldn't find any. If there is an existing issue, please provide a link or suggest an alternative solution if you have one. Below is the link to the codesandbox:

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

Answer №1

&....; represents an HTML Entity, making it work directly in HTML but not in javascript.

To make it usable in javascript, you need to decode it.

You can achieve this by following the method outlined 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;
}

Then, you would use it like this:

const label=decodeHTMLEntities("I&#39;m male");

An alternative and more concise approach in modern javascript is 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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble initiating React in the command prompt

Whenever I attempt to enter npm start in the command prompt, I keep getting an error message saying missing script: start. I've tried adding a start script to the package.json file but it's giving me an error stating failed to parse json. "name ...

Passing an array to a path in React Router Dom V6

I am looking for a way to render the same page using multiple routes in react-router-dom v6, similar to how it was done in v5. However, I have been unable to find an efficient solution. For example, in v5 I could achieve this with the following code: ...

angular failure to assign a variable to $scope

When communicating with the Node server, I am able to receive a response message in the controller. However, there seems to be an issue with assigning it properly. .controller('someCtrl', function(exportExcel){ $scope.clickEvent = function() ...

Implementing JavaScript logic to proceed to the following array within a 3D array once a specific condition is met

I'm currently tackling a challenge that requires me to obtain a specific number using a given 3D array. This array consists of 2D arrays, each containing the same number repeated x times. The parent array is sorted from largest to smallest. Here&apos ...

React - discrepancy in date-fns' differenceInDays function resulting in a NaN output

For some reason, I am encountering a NaN error when attempting to calculate the difference in days between the current date and a product's expiry date in the user's timezone. I have included my code below for reference: import { formatInTimeZone ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Why isn't the JavaScript if statement working properly when checking the length?

Below is an if statement that I have devised: var TotalMoney=0; var Orbs=0; if (TotalMoney.length==2) { Orbs+=1; } The intention behind this code snippet is to increase the value of "Orbs" by 1 when the digit length of "TotalMoney" equals 2. However, it& ...

Tips on generating an HTML element using JavaScript and storing it in a MySQL database

I need help with saving a created element to the database so that it remains on the page even after refreshing. Any assistance would be greatly appreciated. Thank you. document.getElementById("insert").onclick = function(){ if(document.getElementById( ...

Using JQUERY for navigating through pages in a REST API while utilizing deferred functionality

I am utilizing a REST API in jSON format to fetch records. My Approach The REST API retrieves records in jSON format. Initially, I retrieve the top 6 records, along with an additional jSON node containing a forward paging URL. This URL is assigned t ...

How can a component be dynamically rendered in React?

I'm interested in exploring alternative approaches to accomplishing the same task. My desired outcome is as follows: Menu Item 1 Menu Item 2 Menu Item 3 Target (Where component should be displayed) When a menu item is clicked, I want the associate ...

Having trouble getting my React app to launch using the npm start command

Having an issue with my React app. I cloned it from Git and ran the commands npm install and npm start, but encountered the following error: SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) ...

Is there a way to customize Angular's number filter?

I'm trying to achieve a consistent number format with Angular's number filter, regardless of the localization selected. After inspecting the Angular source code on GitHub, I found the implementation of the filter to be like this: function number ...

Utilizing @Material-UI Tabs for a Stylish Navigation Bar

As a newcomer to the coding realm, I find myself on a quest for an answer that has proven elusive. Despite scouring various sources, none of the solutions I've stumbled upon seem to work in my case. The issue at hand revolves around my desire to util ...

JavaScript embedded in an HTML document, which in turn is embedded within JavaScript

Is it possible to nest tags within other tags to control the functionality of a download button in a chat bot? Unfortunately, nesting tags is not allowed, so I'm looking for an alternative solution. Below is the complete HTML file I'm working wit ...

Retrieve a text file using FTP asynchronously and utilizing Promises in Node.js and AWS Lambda

Utilizing a single Node module called basic-ftp, I am tasked with downloading a txt file in AWS Lambda and storing it in the /tmp/ directory within the Lambda function. The goal is to manipulate the txt file and its contents outside of the FTP function. ...

Encountering a Typescript error while attempting to extract state from a History object containing an enum property

My enum structure is as follows: enum values { first, second, } Within my component, I handle the history object like this: const { push, location: { state = {} } } = useHistory(); Additionally, in the same component within a useEffect hook, I have ...

What is the best way to generate a JavaScript variable using information from SQLite?

I found the examples provided in the JavaScript edition of the Missing Manual series to be extremely helpful! OG.Q. I have explored various options but have not been able to find a solution to my problem yet. This is what I am trying to achieve: Save u ...

Ways to retrieve the value from a button when it is clicked

I am facing an issue where I have buttons that are generated dynamically depending on the number of phone numbers available in the database. For example, if there are 3 phone numbers in the database, there will be three buttons displayed. The aim is that w ...

Is there a way to modify the state following a sorting operation?

How can I properly update the state after sorting by salary? state = { workers: [ {name: 'Bob', surname: 'Meljanski', salary: 5140}, {name: 'Michel', surname: 'Hensson', salary: 5420}, {n ...

Exploring the life cycle of React.js components, how state behaves within them, and the asynchronous nature

There seems to be an issue with the expected data result and the actual data result. Even though the fetchData() and fetchnumberOfCommits() methods are being called from the componentWillMount(), the array is empty at first. However, the render method is b ...