Using symbols in JSX and React Native

Viewed 19119

I would like to use this symbol in my React Native project.

I tried using the Unicode encoding like this:

    var arrow = "U+0279C";

And in the JSX:

   <Text>
      {arrow}
   </Text>

However, this just displays the encoding literally: U+0279C.

So any idea how can I use a symbol in JSX?

4 Answers

You should use the HTML code for the symbol.

<Text>
    &#10140;
</Text>

As described in notes below.. (important, quotes don't seem to work)...

Just to clarify: <Text>&#10140;</Text> will work, but <Text>{ '&#10140;' }</Text> will not.

Use this functions for symbols in this format: & # 1 7 4 ;

/**
 * replaces /$#d\+/ symbol with actual symbols in the given string
 * 
 * Returns given string with symbol code replaced with actual symbol
 * 
 * @param {string} name 
 */
export function convertSymbolsFromCode(name = '') {
  let final = null;
  if (name) {
    const val = name.match(/&#\d+;/) ? name.match(/&#\d+;/)[0] : false; // need to check whether it is an actual symbol code
    if (val) {
      const num = val.match(/\d+;/) ? val.match(/\d+;/)[0] : false; // if symbol, then get numeric code
      if (num) {
        final = num.replace(/;/g, '');
      }
    }
    if (final) {
      name = name.replace(/&#\d+;/g, String.fromCharCode(final));
    }
  }
  return name;
}

USAGE

<Text>
   {convertSymbolsFromCode(this.state.unicode)}
 </Text>

The provided answer did not work for me, since I was dynamically retrieving unicode hex codes from an API. I had to pass them as JavaScript into the react-native jsx code.

The following answer worked for me: Concatenate unicode and variable

I used String.fromCodePoint(parseInt(unicode, 16)) and it worked.

Example:

const unicode = unicodeHexValueFromApi //This value equals "05D2"

return(<Text>{String.fromCodePoint(parseInt(unicode, 16))}</Text>)

<Text>{"Any character"}</Text>

This worked for me.

Related