Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using symbols in JSX and React Native

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?

like image 896
octavian Avatar asked Nov 27 '17 14:11

octavian


People also ask

What does {} mean in JSX?

The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string. You need them when you want to use a JavaScript expression like a variable or a reference inside JSX.

Can we use JSX in React Native?

React and React Native use JSX, a syntax that lets you write elements inside JavaScript like so: <Text>Hello, I am your cat!</Text> . The React docs have a comprehensive guide to JSX you can refer to learn even more. Because JSX is JavaScript, you can use variables inside it.


2 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.

like image 200
Mateo Guzmán Avatar answered Sep 30 '22 21:09

Mateo Guzmán


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>
like image 23
Syed SaeedulHassan Ali Avatar answered Sep 30 '22 20:09

Syed SaeedulHassan Ali