In the process of App development, we will use various ICONS. One problem we found in practice is that using images to display ICONS in React Native takes a long time to load. It often takes half a day to load ICONS with blank space. Using a font icon is a good way to solve this problem. What are the benefits of using font ICONS as opposed to images?

The advantages of font ICONS

  1. Based on the Text component to display, fast loading
  2. Font styles can be set to change the size and color of ICONS
  3. Vector icon, zoom in and out without distortion
  4. Good compatibility, suitable for all browsers
  5. Simple design, rich icon library, such as FontAwesome, Iconfont
  6. The most important point, not like the picture as a result of a small change to change, we directly modify the font style on the line ✌️

The most useful library for using font ICONS in React Native is react-native vector-icons. In daily development, this library contains several icon libraries that can basically meet our requirements. If there are still insufficient font ICONS, we can use custom font ICONS.

This article mainly introduces the following content, summary and share the development experience

  1. react-native-vector-iconsDetailed usage method of.
  2. Download the usage method of font icon from Iconfont, the official icon library of Ali, without using other third-party libraries.
  3. react-native-vector-iconsAdvanced usage: Create custom fonts using icon resources downloaded from iconFont.

react-native-vector-iconsThe use of

First, let’s talk about installation and configuration:

Installation and configuration

  1. Use it in the root directorynpm install react-native-vector-icons --saveoryarn add react-native-vector-iconsThe installation.
  2. Run after installation is completereact-native link react-native-vector-iconsCommand link the library
  3. Configuration on Android

After executing the react-native link command, you will find that in the Android directory the library has automatically introduced the font files into app/ SRC /main and created the assets/fonts directory for us

Add the following to the Android /app/build.gradle file:

Vectoricons = [iconFontNames:] // The font files that you want to customize need to be declared here. If there are more than one, you need to add them to the array.'iconfont.ttf']] // If you use only the react-native vector-icons ICONS, just add the following line. You can leave out the apply from configuration:".. /.. /node_modules/react-native-vector-icons/fonts.gradle"
Copy the code
  1. IOS Configuration

After running the react-native link command, you will find a line of Fonts provided by Application in the info.plist file in the iOS project directory. You can also configure this line manually. We need to add all the fonts in react-native-vector-icons as follows:

Build Phase
Link Binary With Libraries
libRNVectorIcons.a

At this point, both sides are configured and ready to go.

The basic use

1. Used as Icon component

import Icon from 'react-native-vector-icons/FontAwesome';

<Icon name={'angle-right'} size={24} color={'# 999'}
Copy the code

Below is a Settings screen using the FontAwesome icon

If you use several library ICONS such as FontAwesome, Ionicons and Feather as Icon component references at the same time, in order to avoid confusion of Icon component names, you can use different names when importing the component name corresponding to the import name.

import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import Icon from 'react-native-vector-icons/Ionicons';

<FontAwesomeIcon name={'angle-right'} size={24} color={'# 999'}/>
<Icon name={'ios-sad'} size={100} color={'# 999999'} / >Copy the code

2. Used as a Button component

import Icon from 'react-native-vector-icons/FontAwesome';

<Icon.Button name="star" backgroundColor="# 999999"OnPress ={this.starongithub}> Give me a star on Github😁 </ icon.button >Copy the code

3. Use as a static image resource

What if we want to display these font ICONS using the Image component instead of the icon component? Look at the code:

import Icon from 'react-native-vector-icons/FontAwesome';

constructor(props) {
    super(props);
    this.state = {
      userIcon: null,
    };
}

componentWillMount() {
    Icon.getImageSource('user', 50, '# 999').then((source) => {
      this.setState({
        userIcon: source})}); }Copy the code

Declare a userIcon in state, then use the Icon component’s getImageSource method to get the Icon resource and assign it to userIcon, and then set the userIcon where the Image component is needed in the Render function.

<Image source={this.state.userIcon}/>
Copy the code

4. Cooperate with TabBarIOS

import Icon from 'react-native-vector-icons/Ionicons';

<Icon.TabBarItemIOS
    title={'Home'}
    iconName={'ios-home-outline'}
    selectedIconName={'ios-home'}
    iconColor={'# 888'}
    selectedIconColor={'#ff0098'} selected={this.state.selectedTabIndex === 0} renderAsOriginal onPress={() => { this.setState({ selectedTabIndex: 0})}} >Copy the code

5. Use in NavigatorIOS components

NavigatorIOS is an iOS proprietary component, and the font icon is mainly used in NavigationBar, which is used in the same way as the static image resource mentioned above. Note that NavigatorIOS does not re-render when the state property values change, so the ICONS on the NavigationBar after getImageSource may not be displayed. Take a look here at the official documentation for React-Native – Vector-icons, which lovingly state the guidelines for avoiding pothole:

Note: Since NavigatorIOS doesn’t rerender with new state and the async nature of getImageSource you must not use it with initialRoute until the icon is rendered, but any view added by push should be fine. Easiest way is to simple add an if statment at the beginning of you render method like this:

render() {
    if(! this.state.myIcon) {return false;
    }
    return(<NavigatorIOS ... / >); }Copy the code

In short, it’s a judgment before it’s evaluated…

6. Use in the ToolbarAndroid component

There are two ways to do this: one is to get a static image resource from the Icon component and use it in the native ToolbarAndroid component, or the other is to use the Icon.

import Icon from 'react-native-vector-icons/FontAwesome';

constructor(props) {
    super(props);
    this.state = {
      appLogo: null,
    };
  }
  
componentWillMount() {
    Icon.getImageSource('android', 36, '#92c029').then((source) => {
      this.setState({
        appLogo: source})}); }render() {
    return (
      <View style={styles.container}>
        <ToolbarAndroid
          style={styles.toolbar_system}
          logo={this.state.appLogo}
          title={'This is an android toolbar'}
        />
        <Icon.ToolbarAndroid
          navIconName={'amazon'}
          style={styles.toolbar_iconfont}
          titleColor="white"
          title={'This is an Icon toolbar'}
        />
      </View>
    )
  }
Copy the code

Ali vector icon library iconfont use

The above mentioned font ICONS are based on third-party library use methods, if you want to use a custom icon, what to do? Here to Ali official icon library to illustrate. The site requires login to download resources.

  1. Select a random set of ICONS from iconfont, add all ICONS to the shopping cart, click on the shopping cart, and click the download code below to download the resource locally.
  2. Unzip the zip file and you can see the following files in the folder:

demo_unicode.html

  1. Copy the iconfont. TTF file to the Android and iOS engineering directories respectively.

Android is placed in the app/SRC/main/assets/fonts folder, and in the app/SRC/build gradle add configuration:

project.ext.vectoricons = [
    iconFontNames: [ 'iconfont.ttf']]Copy the code

I’ve already said that.

For iOS, you need to add iconfont. TTF to your project. You can create a Fonts folder, put iconfont. In the info.plist font provided by Application add a line iconfont. TTF.

Using the principle of

Using the Text component, set the Unicode character to display the icon. The fontFamily of the Text component is set to iconfont, and fontSize can be used to set the font icon size.

If there are multiple ICONS, I want to be lazy and put all unicode characters in an array as strings. Then I use the array map method to loop through the Text component. In this case, the Text component takes the value of string. All ICONS are not displayed properly, all are strings. It turns out that this requires converting unicode strings, such as  Change to \ue6a7.

No more code here, above:

usereact-native-vector-iconsCreate a custom icon library

It’s easy to use Unicode encoding directly, but it’s not very intuitive at the code level, because it’s All Unicode and it’s prone to spelling errors. Using React-native-vector-icons to create custom icon libraries is a better option, which is easier to maintain and avoids errors.

FontAwesome esome is the author of a custom font icon library in React-native Vector-icons.

import createIconSet from './lib/create-icon-set';
import glyphMap from './glyphmaps/FontAwesome.json';

const iconSet = createIconSet(glyphMap, 'FontAwesome'.'FontAwesome.ttf');

export default iconSet;

export const Button = iconSet.Button;
export const TabBarItem = iconSet.TabBarItem;
export const TabBarItemIOS = iconSet.TabBarItemIOS;
export const ToolbarAndroid = iconSet.ToolbarAndroid;
export const getImageSource = iconSet.getImageSource;
Copy the code

The createIconSet method in react-native Vector-icons is used to create the icon library and match the ICONS according to FontAwesome. Json. FontAwesome. Json is a mapping collection of icon names and decimal encoding:

{
  "glass": 61440,
  "music": 61441,
  "search": 61442,... }Copy the code

Now that we have Iconfont. TTF, we can also create a set of font ICONS and use our iconfont the same way FontAwesome and other icon libraries use it.

Generate iconfont. Json

Json file. There is an iconfont. SVG file in which you can find the name of each icon and the corresponding hexadecimal Unicode code and convert the hexadecimal code into decimal. Compose JSON data like FontAwesome. Json above.

But matching icon names and conversion codes one by one is cumbersome and unwieldy, so we use scripts to do this.

Script reference: github.com/zhengcx/RNI… I used the script of the great God.

Sh script file iconfont_mapper.sh and iconfont. SVG in the same directory, open the CLI or terminal, and run the following command:

./iconfont_mapper.sh iconfont.svg
Copy the code

If Permission denied is reported under MAC, modify the file Permission first

chmod 777 iconfont_mapper.sh
Copy the code

Then run the above command to convert iconfont. SVG to a iconfont. Json file.

Create CustomIconFont

Add iconfont. Json to our project and now we can create our custom icon library. Create a CustomIconFont.

import createIconSet from 'react-native-vector-icons/lib/create-icon-set';
import glyphMap from './iconfont.json'; // fontFamily, fontFile, and glyphMap; // fontFamily, fontFile, and glyphMap; // fontFamily, and fontFile. Const iconSet = createIconSet(glyphMap,'iconFont'.'iconfont.ttf');

export default iconSet;

export const Button = iconSet.Button;
export const TabBarItem = iconSet.TabBarItem;
export const TabBarItemIOS = iconSet.TabBarItemIOS;
export const ToolbarAndroid = iconSet.ToolbarAndroid;
export const getImageSource = iconSet.getImageSource;
Copy the code

At this point, I think you already know how to use this icon library, yes, in the same way as the react-native Vector-icons built-in icon library.

Example:

import CustomIconFont from './CustomIconFont'; <CustomIconFont name={'tubiaozhizuomobanyihuifu_'} size={24} color={'#00c06d'Button <CustomIconFont.Button name={'tubiaozhizuomobanyihuifu_23'} backgroundColor={'#59ACEA'}>
    Test icon button
</CustomIconFont.Button>
Copy the code

Finally, attach a rendering:

Full code address: github.com/mrarronz/re… , Chapter9-IconfontExample