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

Removing the navigation button from the hamburger menu

I am working on creating a semi-progressive top navigation bar. For the mobile viewport, the navigation bar will only display the logo and a hamburger button. When the button is clicked, various navigation menu options as well as the Log In and Sign Up bu ...

Exploring the Utilization of FormData and form.serialize within the Data Parameter of Ajax Jquery

My form includes a multiupload uploader for files, structured like this : <div class="col-md-4"> <div class="form-group"> <label class="control-label col-md-3">Location</label> <div class="col-md-9"> <?php ...

Tips for effectively incorporating additional directives into a directive as it is being defined

I'm encountering a significant issue with dynamic directives in angularjs. My goal is to include new directives to a directive while defining it through an object: compile: function () { return { pre: function (scope, iElement, iAttrs) { ...

Input a new value into the registration field to update it

My current task involves adding a new text field to a React form using a button. I need this new input text field to be able to store data on a register. How can I go about setting this property? Typically, when creating a text field, you would utilize co ...

Unveiling the power of localStorage in Next.js to enhance initial rendering

I've implemented a switch between light and dark themes on my website, with the state saved in localStorage. Ensuring that the initial browser render displays the correct theme is my current goal. Here's the code snippet that I'm using wit ...

The most effective method for transferring asynchronous data to pages in Next.js

My current directory structure: - components - NavBar - Header - Layout - pages - pages - demo.js - _app.js - index.js // index.js import React from 'react'; import NewLayout from "../../components/NewLayout/NewLayou ...

What steps should I follow to ensure that the processData function waits for the data returned by the getData function in Angular?

After calling the getData function, each object is stored in an array and returned. Now I need the processData function to await these results from getData and then further process them. However, when I try to console.log(cleaningData), I don't see an ...

Store the incoming documents from xmpp using the Strophe si-filetransfer feature

I am currently working on adding file transfer functionality to my web application using the strophe.si-filetransfer.js plugin. I have successfully received file details within an iq stanza. My inquiry is, how can I extract the file data from this iq stanz ...

The attempt to cast to a number for the value of "[object Object]" at the specified path failed in mongoose

My schema is structured like this: module.exports = mongoose.model('Buyer',{ username: String, password: String, email: String, url: String, id: String, firstName: String, lastName: String, credit: Number, }); Wh ...

Unlock the secrets of obtaining data in React-Native by deciphering what happens when the switch is

I need to retrieve information about the status of a switch and use this data in other files. Following that, I want to create an IF statement for StyleSheet. const DarkLightSwitch = () => { const [lock, setLock] = useState(); return ( &l ...

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

Platform Independent Data Storage Solution

Looking to create a Cross-browser compatible Web Application using HTML, JS, and CSS. In need of a robust database storage solution that can be queried on the client side using JS. While Web SQL/SQLite seems like a good option, it lacks support in IE. Does ...

One common issue is being unable to target input[type=file] when multiple forms are present on a page using JavaScript

Question: I have multiple dynamic forms on a web page, each with a file input field. How can I specifically target the correct file input using $(this) in JavaScript? Here is an example of one of my forms: <form enctype="multipart/form-data" action="c ...

Conceal any elements designated by a particular class and reveal them based on their corresponding ID

I have utilized jQuery's hide() function to initially hide all elements of a specific class when the page loads. My goal is to make individual elements visible again based on their unique IDs when a corresponding link is clicked. In total, there are ...

Tips for incorporating an SVG image into a Next.js application while being able to dynamically change its color

I currently have 13 apps within the app directory, and I am attempting to display an icon in a component. While I was successful in achieving this, I am having trouble changing the color of the SVG image. Is there a way to modify the coloring of the SVG ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

There seems to be a problem with the external JavaScript file not functioning

After dragging and dropping the .js file into my ASP.NET project, I am facing an issue where it remains unresponsive, even though the code works fine when used inline. This problem is occurring while using VS 2017. Here is a snippet of my code: <scrip ...

An unanticipated error event occurred while executing the create react app command

After successfully working with reactjs for a while, I decided to create a new application using create-react-app my-new-app. However, when I tried executing npm start, I encountered an error as shown in this screenshot https://ibb.co/qrN6YZ6. Can anyone ...

What is the best way to add the current date to a database?

code: <?php session_start(); if(isset($_POST['enq'])) { extract($_POST); $query = mysqli_query($link, "SELECT * FROM enquires2 WHERE email = '".$email. "'"); if(mysqli_num_rows($query) > 0) { echo '<script&g ...

Expressjs: Validating google-auth-library ID token "token has expired, please try again..."

I attempted to implement Google authentication login for my ReactJS/ExpressJS web application. Utilizing the react-google-login package on the frontend has been crucial: import React from "react" import { GoogleLogin } from "react-google-log ...