Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React keeps escaping the amp character (&) in attributes

I have a component with a data-icon attribute. The value of this attribute should be, for instance, &#xf00f so that css can render it via content: attr( data-icon );.

However, whatever I try: React keeps escaping to &. Even when I provide the proper unicode character \u0026#xf00f.

Is there some way to stop React from messing with that value? Besides dangerously setting inner html, as I do not want to add another wrapper.

Component

define( [ 'react', 'util' ], function( React, Util )
{
    return React.createClass(
    {
        render: function()
        {
            //var amp = '\u0026',
            var amp = String.fromCharCode( 38 ),    
            // Util.icons[x] returns a String, such as "f00f"
            code = amp + '#x' + Util.icons[this.props.name] + ';';

            return (
                <i data-icon={code}>
                    {this.props.children ? <span>{this.props.children}</span> : null}
                </i>
            );
        }
    } );
} );

Usage

<Widget.Icon name="add" />

Output

<i data-icon="&amp;#xf0fb;" data-reactid=".170lse36465.7.0"></i>
like image 625
Taig Avatar asked Apr 27 '15 22:04

Taig


People also ask

Why does & Change To &amp?

The & character is special in HTML because it starts a number of codes known as HTML Entities. To represent this special character, when writing HTML, you write &amp; and the browser displays it as &.

Does React automatically escape HTML?

React applies auto-escaping As a result, React will automatically ensure that data that ends up in the page will not cause XSS attacks.

What is Escape character React?

To use escape characters in JSX React components, we can use the same ones as plain JavaScript. JavaScript escape characters include: ' single quote. " double quote. \ backslash.

Can we use AMP With React?

I am assuming you already have a React app and you are happy. You can opt-in to AMP on a page-by-page basis, and that's exactly what you should do. Most importantly, make sure to measure exactly how AMP performs while stepping into the waters slowly.


1 Answers

Well, I just realized, that for my particular use case I can simply get away with:

<i data-icon={String.fromCharCode( "f00f" )} />

https://github.com/facebook/react/issues/3769

like image 85
Taig Avatar answered Sep 26 '22 04:09

Taig