Search code examples
reactjsreact-nativeiconsfont-awesomefont-awesome-5

Font Awesome & Unicode & Variable in React-Native


I want to show fontAwesome icons in my app.

I can show with string type icons like this:

<Text style={{fontFamily: 'fontAwesome'}}>&#xf0e8;</Text> print icon. Working well.

But I need to show icons with variable like this:

let icon2 = "&#xf0e8;";
<Text style={{fontFamily: 'fontAwesome'}}>{icon}</Text>

then print to screen &#xf0e8; not icon.

I share with you expo snack link. You can try this easily.

https://snack.expo.io/@wyrustaaruz/Zm9udG


Solution

  • Instead of

    let icon2 = "&#xf0e8;";
    

    you need to define it as;

    let icon2 = "\uf0e8";
    

    In javascript, you need to define unicode characters with "\u" when you assign it to a variable. So it can recognize and parse unicode characters properly.

    Edited for your question in your comment;

    Your icons are hexadecimal. So we can delete first 3 character from icon. After that, we parse that unicode value as integer and we can convert to a unicode string by String.fromCharCode.

    icon2 = icon2.substr(3);
    icon2 = String.fromCharCode(parseInt(icon2, 16));