React: encoded character in table td tags showing as string incorrectly

Created on 28 Apr 2018  路  3Comments  路  Source: facebook/react

Encoded characters for example &pound;, &#36; can not show as 拢, $ if adding it into <td>. These characters are fine if put it into h1 tag for example as long as outside of table.

<tr>
   <th scope="row">1</th>
   <td>USD</td>
   <td>&#36;</td>
   <td>United States Dollar</td>
   <td>9,120.6025</td>
   <td>9120.6025</td>
</tr>
Needs More Information

Most helpful comment

I think what you are seeing here is the difference between: <td>{"&pound;"}</td> and <td>&pound;</td> (note that the first is a string literal within a jsx expression, and the second is regular jsx text) these two things are subtly different.

This also still happens for other html elements like an h1, or a span:

<span>{"&pound;"}</span>
// renders the following html
<span>&pound;</span>

To get around this, if you have control over the encoded characters, instead of storing them as strings, you can wrap them in a <React.Fragment>, or if you don't have control over the characters (i.e. they are coming from an API response) you will need to use dangerouslySetInnerHTML like so:

<td dangerouslySetInnerHTML={{__html: item.symbol}} />

All 3 comments

Can you provide a fiddle please?

I think what you are seeing here is the difference between: <td>{"&pound;"}</td> and <td>&pound;</td> (note that the first is a string literal within a jsx expression, and the second is regular jsx text) these two things are subtly different.

This also still happens for other html elements like an h1, or a span:

<span>{"&pound;"}</span>
// renders the following html
<span>&pound;</span>

To get around this, if you have control over the encoded characters, instead of storing them as strings, you can wrap them in a <React.Fragment>, or if you don't have control over the characters (i.e. they are coming from an API response) you will need to use dangerouslySetInnerHTML like so:

<td dangerouslySetInnerHTML={{__html: item.symbol}} />
Was this page helpful?
0 / 5 - 0 ratings