Giter Site home page Giter Site logo

oblador / react-native-vector-icons Goto Github PK

View Code? Open in Web Editor NEW
17.2K 207.0 2.1K 15.03 MB

Customizable Icons for React Native with support for image source and full styling.

Home Page: https://oblador.github.io/react-native-vector-icons/

License: MIT License

JavaScript 55.95% Objective-C 1.22% Smarty 1.01% Java 9.91% Ruby 1.05% HTML 1.21% CSS 2.72% Shell 18.80% Objective-C++ 8.12%
react-native icon icon-pack ui

react-native-vector-icons's Introduction

Vector Icons for React Native

Travis npm npm

React Native Vector Icons

Elevate your React Native applications with the power of customizable vector icons. Ideal for embellishing buttons, logos, and navigation or tab bars, these icons seamlessly integrate into your projects. Their versatility makes extension and styling effortless.

For the integration of .svg files natively, you can explore react-native-vector-image.

Table of Contents

Sponsorship

Should you find this library beneficial, kindly contemplate the option of sponsoring. Our envisioned endeavors encompass the restructuring of the repository into a monorepo architecture. This transition will empower independent versioning of icon sets, enhance performance, reduce bundle size, and simplify community contributions. Your sponsorship plays a pivotal role in materializing these advancements.

Bundled Icon Sets

Explore all icons.

  • AntDesign from AntFinance (298 icons)
  • Entypo by Daniel Bruce (v1.0.1 with 411 icons)
  • EvilIcons designed by Alexander Madyankin & Roman Shamin (v1.10.1 with 70 icons)
  • Feather created by Cole Bemis & Contributors (v4.28.0 featuring 286 icons)
  • FontAwesome by Dave Gandy (v4.7.0 containing 675 icons)
  • FontAwesome 5 from Fonticons, Inc. (v5.15.3 offering 1598 free and 7848 pro icons)
  • FontAwesome 6 designed by Fonticons, Inc. (v6.1.2 featuring 2016 free and 16150 pro icons)
  • Fontisto created by Kenan Gündoğan (v3.0.4 featuring 615 icons)
  • Foundation by ZURB, Inc. (v3.0 with 283 icons)
  • Ionicons crafted by Ionic (v7.1.0 containing 1338 icons)
  • MaterialIcons by Google, Inc. (v4.0.0 featuring 2189 icons)
  • MaterialCommunityIcons from MaterialDesignIcons.com (v6.5.95 including 6596 icons)
  • Octicons designed by Github, Inc. (v16.3.1 with 250 icons)
  • Zocial by Sam Collins (v1.4.0 with 100 icons)
  • SimpleLineIcons crafted by Sabbir & Contributors (v2.5.5 with 189 icons)

Installation

  1. Install the package via npm:
    npm install --save react-native-vector-icons
  2. Depending on the platform you're targeting (iOS/Android/Windows), follow the appropriate setup instructions.
  3. If you're planning to use FontAwesome 5 or 6 icons, refer to these guides: FontAwesome 5 | FontAwesome 6

iOS Setup

To use the bundled icons on iOS, follow these steps:

  • Navigate to node_modules/react-native-vector-icons and drag the Fonts folder (or select specific fonts) into your Xcode project.

    • Make sure your app is checked under "Add to targets," and if adding the whole folder, check "Create groups."
    • Not familiar with Xcode? Check out this article.
  • Edit Info.plist and add a property called Fonts provided by application (or UIAppFonts if Xcode autocomplete is not working):

    • List of all available fonts to copy & paste in Info.plist
      <key>UIAppFonts</key>
      <array>
        <string>AntDesign.ttf</string>
        <string>Entypo.ttf</string>
        <string>EvilIcons.ttf</string>
        <string>Feather.ttf</string>
        <string>FontAwesome.ttf</string>
        <string>FontAwesome5_Brands.ttf</string>
        <string>FontAwesome5_Regular.ttf</string>
        <string>FontAwesome5_Solid.ttf</string>
        <string>FontAwesome6_Brands.ttf</string>
        <string>FontAwesome6_Regular.ttf</string>
        <string>FontAwesome6_Solid.ttf</string>
        <string>Foundation.ttf</string>
        <string>Ionicons.ttf</string>
        <string>MaterialIcons.ttf</string>
        <string>MaterialCommunityIcons.ttf</string>
        <string>SimpleLineIcons.ttf</string>
        <string>Octicons.ttf</string>
        <string>Zocial.ttf</string>
        <string>Fontisto.ttf</string>
      </array>

    Above step might look something like this:

    XCode screenshot

  • In Xcode, select your project in the navigator, choose your app's target, go to the Build Phases tab, and under Copy Bundle Resources, add the copied fonts.

  • When using auto linking, it will automatically add all fonts to the Build Phases, Copy Pods Resources. Which will end up in your bundle. To avoid that, create a react-native.config.js file at the root of your react-native project with:

      module.exports = {
        dependencies: {
          'react-native-vector-icons': {
            platforms: {
              ios: null,
            },
          },
        },
      };

Note: Recompile your project after adding new fonts.

Android Setup

Option: With Gradle (recommended)

To make font management smoother on Android, use this method:

  • Edit android/app/build.gradle (NOT android/build.gradle) and add:

    apply from: file("../../node_modules/react-native-vector-icons/fonts.gradle")

    To customize the fonts being copied, use:

    project.ext.vectoricons = [
        iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Specify font files
    ]
    
    apply from: file("../../node_modules/react-native-vector-icons/fonts.gradle")
    
Monorepo configuration
If working in a monorepo, point to the correct paths of the `fonts.gradle` script and of the Font files, relative to the android/app/build.gradle file. Example structure:
your-monorepo/
├─ node_modules/
│  ├─ react-native-vector-icons
├─ apps/
│  ├─ YourApp/
│  │  ├─ android/
│  │  │  ├─ app/
│  │  │  │  ├─ build.gradle

Update paths like:

project.ext.vectoricons = [
+ iconFontsDir: "../../../../node_modules/react-native-vector-icons/Fonts",
  iconFontNames: ["YourFont.ttf", "..."]
]

- apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
+ apply from: "../../../../node_modules/react-native-vector-icons/fonts.gradle

⚠️ Reported issues have arisen when utilizing RNVI versions earlier than 9.0.0 within a monorepo context. Therefore, it's advisable to ensure your RNVI version is 9.0.0 or later.

Option: Manual Integration

To manually integrate the library, follow these steps:

  • Copy the contents from the Fonts folder and paste them into android/app/src/main/assets/fonts (ensure the folder name is lowercase, i.e., fonts).

Integrating Library for getImageSource Support

The following steps are optional and are only necessary if you intend to utilize the Icon.getImageSource function.

  • Edit the android/settings.gradle file as shown below:

    rootProject.name = 'MyApp'
    
    include ':app'
    
    + include ':react-native-vector-icons'
    + project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
  • Edit the android/app/build.gradle (located in the app folder) as shown below:

    apply plugin: 'com.android.application'
    
    android {
      ...
    }
    
    dependencies {
      implementation fileTree(dir: "libs", include: ["*.jar"])
      //noinspection GradleDynamicVersion
      implementation "com.facebook.react:react-native:+"  // From node_modules
    
    + implementation project(':react-native-vector-icons')
    }
  • Edit your MainApplication.java (located deep within android/app/src/main/java/...) as shown below (note that there are two places to edit):

    package com.myapp;
    
    + import com.oblador.vectoricons.VectorIconsPackage;
    
    ....
    
      @Override
      protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
          new MainReactPackage()
    +   , new VectorIconsPackage()
        );
      }

Please note that this optional step is necessary only if your react-native app doesn't support auto-linking; otherwise, you can skip this.

macOS Setup

via react-native-macos

To set up the library on your macOS project using react-native-macos, follow these steps:

  1. Browse to the node_modules/react-native-vector-icons folder and drag the Fonts folder into your project in Xcode. Ensure that your app is checked under "Add to targets," and select "Create folder references" when prompted.

  2. Edit your Info.plist and include a new property named Application fonts resource path (or ATSApplicationFontsPath if Xcode's autocomplete isn't functioning or you're not using Xcode). Set the value of this property to Fonts.

Please note that after adding new fonts, you need to recompile your project. Also, make sure that the Fonts folder is present under the Copy Bundle Resources section within the Build Phases of your Xcode project.

These steps will effectively integrate the vector icons library into your macOS project while utilizing the react-native-macos framework.

Windows Setup

via react-native-windows

To set up the library on your Windows project using react-native-windows, follow these steps:

  1. In the top-level projects (/windows/project-name/Assets), copy and paste the font files.

  2. Open your solution in Visual Studio:

    a. Right-click the Assets folder in your solution. b. Select Add > Existing Item. c. Browse and select the fonts that you copied into /windows/project-name/assets. d. Click Add.

Please note that after adding new fonts, you need to recompile your project.

By following these steps, you'll seamlessly integrate the vector icons library into your Windows project, leveraging the react-native-windows framework.

Web Setup

To integrate the library with your web project using webpack, follow these steps:

  1. In your webpack configuration file, add a section to handle TTF files using url-loader or file-loader:

    {
      test: /\.ttf$/,
      loader: "url-loader", // or directly file-loader
      include: path.resolve(__dirname, "node_modules/react-native-vector-icons"),
    }
  2. In your JavaScript entry point, consume the font files and inject the necessary style tag:

      // Use the prebuilt version of RNVI located in the dist folder
      import Icon from 'react-native-vector-icons/dist/FontAwesome';
    
      // Generate the required CSS
      import iconFont from 'react-native-vector-icons/Fonts/FontAwesome.ttf';
      const iconFontStyles = `@font-face {
        src: url(${iconFont});
        font-family: FontAwesome;
      }`;
    
      // Create a stylesheet
      const style = document.createElement('style');
      style.type = 'text/css';
    
      // Append the iconFontStyles to the stylesheet
      if (style.styleSheet) {
        style.styleSheet.cssText = iconFontStyles;
      } else {
        style.appendChild(document.createTextNode(iconFontStyles));
      }
    
      // Inject the stylesheet into the document head
      document.head.appendChild(style);

By following these steps, you will seamlessly integrate the vector icons library into your web project using webpack, enabling you to effortlessly use the icons within your web application.

Upgrading

Upgrading this package often requires the font files linked to your projects to be updated as well. If the automatic linking works for you, running this again should update the fonts. Otherwise you need to follow the steps outlined in the installation section.

Icon Component

You can either use one of the bundled icons above or roll your own custom font.

import Icon from 'react-native-vector-icons/FontAwesome';
const myIcon = <Icon name="rocket" size={30} color="#900" />;

Properties

Any Text property and the following:

Prop Description Default
size Size of the icon, can also be passed as fontSize in the style object. 12
name What icon to show, see Icon Explorer app or one of the links above. None
color Color of the icon. Inherited

Static Methods

Prop Description
getFontFamily Returns the font family that is currently used to retrieve icons as text. Usage: const fontFamily = Icon.getFontFamily()
getImageSource Returns a promise that resolving to the source of a bitmap version of the icon for use with Image component et al. Usage: const source = await Icon.getImageSource(name, size, color)
getImageSourceSync Same as getImageSource but synchronous. Usage: const source = Icon.getImageSourceSync(name, size, color)
getRawGlyphMap Returns the raw glyph map of the icon set. Usage: const glyphMap = Icon.getRawGlyphMap()
hasIcon Checks if the name is valid in current icon set. Usage: const isNameValid = Icon.hasIcon(name)

Styling

Since Icon builds on top of the Text component, most style properties will work as expected, you might find it useful to play around with these:

  • backgroundColor
  • borderWidth
  • borderColor
  • borderRadius
  • padding
  • margin
  • color
  • fontSize

NOTE: On android Text doesn't currently support border* styles, to circumvent this simply wrap your Icon with a View.

By combining some of these you can create for example :

type star

Icon.Button Component

A convenience component for creating buttons with an icon on the left side.

import Icon from 'react-native-vector-icons/FontAwesome';
const myButton = (
  <Icon.Button
    name="facebook"
    backgroundColor="#3b5998"
    onPress={this.loginWithFacebook}
  >
    Login with Facebook
  </Icon.Button>
);

const customTextButton = (
  <Icon.Button name="facebook" backgroundColor="#3b5998">
    <Text style={{ fontFamily: 'Arial', fontSize: 15 }}>
      Login with Facebook
    </Text>
  </Icon.Button>
);

buttons

Properties

Any Text, TouchableHighlight or TouchableWithoutFeedback property in addition to these:

Prop Description Default
color Text and icon color, use iconStyle or nest a Text component if you need different colors. white
size Icon size. 20
iconStyle Styles applied to the icon only, good for setting margins or a different color. Note: use iconStyle for margins or expect unstable behaviour. {marginRight: 10}
backgroundColor Background color of the button. #007AFF
borderRadius Border radius of the button, set to 0 to disable. 5
onPress A function called when the button is pressed. None

Usage as PNG Image/Source Object

Convenient way to plug this in into other components that rely on bitmap images rather than scalable vector icons. Takes the arguments name, size and color as described above.

Icon.getImageSource('user', 20, 'red').then(source =>
  this.setState({ userIcon: source })
);

Alternatively you may use the synchronous method Icon.getImageSourceSync to avoid rendering glitches. Keep in mind that this method is blocking and might incur performance penalties. Subsequent calls will use cache however.

Multi-Style Fonts

Some fonts today use multiple styles, FontAwesome 5 for example, which is supported by this library. The usage is pretty much the same as the standard Icon component:

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

const myIcon1 = <Icon name="comments" size={30} color="#900" />; // Defaults to regular
const myIcon2 = <Icon name="comments" size={30} color="#900" solid />;
const myIcon3 = <Icon name="comments" size={30} color="#900" light />; // Only in FA5 Pro

Static methods

All static methods from Icon is supported by multi-styled fonts.

Prop Description
getFontFamily Returns the font family that is currently used to retrieve icons as text. Usage: const fontFamily = Icon.getFontFamily(style)
getImageSource Returns a promise that resolving to the source of a bitmap version of the icon for use with Image component et al. Usage: const source = await Icon.getImageSource(name, size, color)
getImageSourceSync Same as getImageSource but synchronous. Usage: const source = Icon.getImageSourceSync(name, size, color)
getRawGlyphMap Returns the raw glyph map of the icon set. Usage: const glyphMap = Icon.getRawGlyphMap(style)
hasIcon Checks if the name is valid in current icon set. Usage: const isNameValid = Icon.hasIcon(name, style)
getStyledIconSet Use this to get a Icon component for a single style. Usage. const StyledIcon = Icon.getStyledIconSet(style)

If no style argument is passed (or if it's invalid) the methods will default to a pre-defineds fallback.

Components

Icon.Button is supported, usage is just like Icon:

import Icon from 'react-native-vector-icons/FontAwesome5';
const myButton = (
  <Icon.Button name="facebook" onPress={this.loginWithFacebook} solid>
    Login with Facebook
  </Icon.Button>
);

Custom Fonts

createIconSet(glyphMap, fontFamily[, fontFile])

Returns your own custom font based on the glyphMap where the key is the icon name and the value is either a UTF-8 character or it's character code. fontFamily is the name of the font NOT the filename. Open the font in Font Book.app or similar to learn the name. Optionally pass the third fontFile argument for android support, it should be the custom font file name.

import { createIconSet } from 'react-native-vector-icons';
const glyphMap = { 'icon-name': 1234, test: '∆' };
const Icon = createIconSet(glyphMap, 'FontName', 'font-name.ttf');

createIconSetFromFontello(config[, fontFamily[, fontFile]])

Convenience method to create a custom font based on a fontello config file. Don't forget to import the font as described above and drop the config.json somewhere convenient in your project.

import { createIconSetFromFontello } from 'react-native-vector-icons';
import fontelloConfig from './config.json';
const Icon = createIconSetFromFontello(fontelloConfig);

createIconSetFromIcoMoon(config[, fontFamily[, fontFile]])

import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import icoMoonConfig from './selection.json';
const Icon = createIconSetFromIcoMoon(
  icoMoonConfig,
  'LineAwesome',
  'line-awesome.ttf'
);

Make sure you're using the Download option in IcoMoon, and use the .json file that's included in the .zip you've downloaded. You'll also need to import the .ttf font file into your project, following the instructions above.

createMultiStyleIconSet(styles [, options])

import { createMultiStyleIconSet } from 'react-native-vector-icons';

/*
 * This is just example code, you are free to
 * design your glyphmap and styles to your liking
 */

import glyphmap from './glyphmap.json';
/*
 * glyphmap = {
 *   "style1": [
 *     "hello",
 *     "world"
 *   ],
 *   "style2": [
 *     "foo",
 *     "bar"
 *   ]
 * }
 */

const glyphKeys = Object.keys(glyphmap); /* ["style1", "style2"] */
const options = {
  defaultStyle: 'style1',
  glyphValidator: (name, style) => glyphKeys.indexOf(name) !== -1,
  fallbackFamily: (name) => {
    for (let i = 0; i < glyphKeys.length; i++) {
      const style = glyphKeys[i];
      if (glyphmap[style].indexOf(name) !== -1) {
        return style;
      }
    }

    /* Always return some family */
    return glyphKeys[0];
  }
};

/*
 * The styles object consits of keys, which will be
 * used as the styles later, and objects which are
 * used as style objects for the font. The style
 * should have unique characteristics for each font
 * in order to ensure that the right one will be
 * chosen. FontAwesome 5 uses font weight since
 * 5.7.0 in order to diffirentiate the styles but
 * other properties (like fontFamily) can be used.
 * It's just a standard RN style object.
 */
const styles = {
  style1: {
    fontWeight: '700'
  },
  style2: {
    fontWeight: '100'
  }
};

const Icon = createMultiStyleIconSet(styles, options);

/* Uses default style (style1) */
<Icon name={'hello'} />
<Icon name={'world'} style1 />
/* Default style is style1 but this will fall back to style2 */
<Icon name={'foo'} />
/* This will also fall back to style2 */
<Icon name={'foo'} style1 />
/* Regular use of style2 */
<Icon name={'bar'} style2 />
option Description default
defaultStyle The name of the style to be used if no style is supplied during rendering. Object.keys(styles)[0]
fallbackFamily Function for selecting a family if a glyph is not available. The function should accept the name of the glyph as a parameter. Returns the name if the family. (name) => Object.keys(styles)[0]
glyphValidator Function for validating that a glyph is available for a chosen style. It has name and style as parameters, in that order. Returns true if the glyph is valid or false if it's not. (name, style) => true

iOS

You have to manually make a reference of your .ttf on your xcodeproj Resources folder and in Info.plist.

Animation

React Native comes with an amazing animation library called Animated. To use it with an icon, simply create an animated component with this line: const AnimatedIcon = Animated.createAnimatedComponent(Icon). You can also use the higher level animation library react-native-animatable.

Usage Examples

IconExplorer

Try the IconExplorer project in Examples/IconExplorer folder, there you can also search for any icon.

Screenshot of IconExplorer

Basic Example

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

function ExampleView(props) {
  return <Icon name="ios-person" size={30} color="#4F8EF7" />;
}

TabBar

Since TabBarIOS was removed from core in favor of @react-navigation/bottom-tabs, it is also removed as a convenience component from this library. Simply use the Icon instead, but don't forget to import and link to this project as described above first.

Below is an example taken from react-navigation:

import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Tab.Navigator
      initialRouteName="Feed"
      screenOptions={{
        activeTintColor: '#e91e63',
      }}
    >
      <Tab.Screen
        name="Feed"
        component={Feed}
        options={{
          tabBarLabel: 'Home',
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="home" color={color} size={size} />
          ),
        }}
      />
      <Tab.Screen
        name="Notifications"
        component={Notifications}
        options={{
          tabBarLabel: 'Updates',
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="bell" color={color} size={size} />
          ),
          tabBarBadge: 3,
        }}
      />
      <Tab.Screen
        name="Profile"
        component={Profile}
        options={{
          tabBarLabel: 'Profile',
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="account" color={color} size={size} />
          ),
        }}
      />
    </Tab.Navigator>
  );
}

ToolbarAndroid

Since ToolbarAndroid was removed from core, it is also removed as a convenience component from this library. Simply use getImageSourceSync instead, but don't forget to import and link to this project as described above first.

import ToolbarAndroid from '@react-native-community/toolbar-android';
import Icon from 'react-native-vector-icons/Ionicons';

const navIcon = Icon.getImageSourceSync('md-arrow-back', 24, 'white');
const overflowIcon = Icon.getImageSourceSync('md-more', 24, 'white');
const settingsIcon = Icon.getImageSourceSync('md-settings', 30, 'white');
const twitterIcon = Icon.getImageSourceSync('logo-twitter', 25, '#4099FF');

function ToolbarView(props) {
  return (
    <ToolbarAndroid
      title="Home"
      titleColor="white"
      navIcon={navIcon}
      onIconClicked={props.navigator.pop}
      actions={[
        {
          title: 'Settings',
          icon: settingsIcon,
          show: 'always',
        },
        {
          title: 'Follow me on Twitter',
          icon: twitterIcon,
          show: 'ifRoom',
        },
      ]}
      overflowIcon={overflowIcon}
    />
  );
}

Inline Icons

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

function ExampleView(props) {
  return (
    <Text>
      Lorem <Icon name="ios-book" color="#4F8EF7" /> Ipsum
    </Text>
  );
}

Generating Your Own Icon Set from a CSS File

If you already have an icon font with associated CSS file then you can easily generate a icon set with the generate-icon script.

Example usage:

./node_modules/.bin/generate-icon path/to/styles.css --componentName=MyIcon --fontFamily=myicon > Components/MyIcon.js

Options

Any flags not listed below, like --componentName and --fontFamily, will be passed on to the template.

-p, --prefix

CSS selector prefix [default: ".icon-"]

-t, --template

Template in JS template string format [default: "./template/iconSet.tpl"]

For default template please provide --componentName and --fontFamily.

-o, --output

Save output to file, defaults to STDOUT

Troubleshooting

The icons show up as a crossed out box on Android

  • Make sure you've copied the font to android/app/src/main/assets/fonts.
  • Delete the build folder with rm -rf android/app/build.
  • Recompile the project.

Red screen with "Unrecognized font family" error on iOS

  • Make sure you've added manually the reference of your .ttf on your xcodeproj Resources folder.
  • Check that the font you are trying to use appears in Info.plist, if you've added the whole folder and it's blue in color, then you need to add it to the path.
  • Check that the font is copied in the Copy Bundle Resources in Build Phases.
  • Delete the build folder with rm -rf ios/build
  • Recompile the project.

Android build fails on Windows for no good reason

Both npm and android file hierarchies tend to get very deep and even worse when you combine them. Since Windows file system has a max length, long file name addresses will result in numerous errors including Execution failed for task ':react-native-vector-icons:processReleaseResources'. So try to keep the path to your project folder as short as possible.

Wrong icons are shown after upgrading this package

You probably didn't update the font files linked to your native project after upgrading. However, this only applies to Android targets since iOS bundles the fonts when building the app (try to clean your build from Xcode if the problem exists). On android you can relink the project or you manually update the fonts. To have them automatically synced use the gradle approach.

Some icons are missing after upgrading this package

Sometimes vendors decides to remove some icons from newer releases, this has nothing to do with this package. If you depend on an older version of a font you can add it as a custom font.

License

This project is licenced under the MIT License.

Any bundled fonts are copyright to their respective authors and mostly under MIT or SIL OFL.

react-native-vector-icons's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-vector-icons's Issues

a lot of padding

For some reason when I add a big icon there is a lot of space surrounding it (see image).
I render it like this:
<Icon style={styles.backChevron} name='chevron-left' size=40 />

screen shot 2015-09-24 at 16 21 37

What am I missing?

Why does project use es6 syntax?

I can not compile any more, webpack throws exception

/node_modules/react-native-vector-icons/lib/create-icon-set.js Line 9: Unexpected token {
You may need an appropriate loader to handle this file type.
| var _ = require('lodash');
| var React = require('react-native');
| var {
|   View,
|   Text,
 @ ./~/react-native-vector-icons/FontAwesome.js 9:20-52

Inline style and padding

Hi again!

Just updated from 0.6, which broke a lot of what I previously did, which was basically this:

<Icon name="ios-chatbubble-outline" style={styles.icon} size={20} color="#999">
  <Text style={styles.iconText}>{this.state.numComments}</Text>
</Icon>

previously documented as the inline styling of elements, to this:

<Text style={styles.iconText}>
  <Icon name="ios-chatbubble-outline" style={styles.icon} size={20} color="#999" />
  {this.state.numComments}
</Text>

The issue is that previous padding and line height options - which worked really well on 0.6 - don't seem to work anymore.. How - in this new inline version - should I add padding between the text and icon? how to vertical align both of them?

Thanks & cheers!

Warning in console for Icon.TabBarItem

I got warning in console but everything in simulator works fine.

Warning: Failed propType: Invalid prop `icon` of type `string` supplied to `RCTTabBarItem`, expected `object`.

My codes:

var Icon = require('react-native-vector-icons/FontAwesome');

...
        <Icon.TabBarItem
          iconName='bar-chart'
          title='DASHBOARD'
          iconSize={24}
          selected={this.state.selectedTab === 'DASHBOARD'}
          onPress={() => {
            this.setState({
              selectedTab: 'DASHBOARD',
            });
          }}>
          <Dashboard />
        </Icon.TabBarItem>
...

Do I miss anything?

Module is undefined

I npm installed, followed every little detail in the readme for XCode. Everything checks.

As soon as I create an Icon it says the Module is undefined and to try restarting the packager.

Cant seem to get it to work. Any clue? Tomorrow at work I'll add more information about the error.

Im including it just like in the example 'react-native-vector-icons/FontAwesome'

Navigator

Great solution for TabBar! Any change we can have the same for the navigator?

Use ionicons.

How to use ionicons which have more than one word? If I use the hyphen, it is putting out a question mark.

ETA for mature Android support?

Hi there :)

Great library, but it seems like it needs some more work on the Android side.

When do you think it will be mature enough on Android to drop the "experimental" tag and have complete docs?

Icon in a TouchableOpacity

When having an Icon in a TouchableOpacity without having a View around the Icon, it crashes on click as it can't find a ref to set the new opacity value on:

      // Reset immediately if POP is unavailable
      this.refs[CHILD_REF].setNativeProps({
        opacity: value
      });

Can be very easily fixed by just putting a View around the Icon, but wanted to mention it anyway. :)

Where is libRNVectorIcons.a ?

I can't seem to find the libRNVectorIcons.a file in the project. Was it removed for some reason? I'm getting an "RNVectorIconsManager not available".
Thanks.

Must check "Create groups" when adding files to Xcode project

When I added the font files to my Xcode project the first time, I simply checked "Create folder references" vs. "Create groups" under the "Added folders" option. React Native couldn't find any of the icon font families, so the font files were not making it in the bundle. I tried adding files again and checked "Create groups" and it worked. If this is not an isolated case, you should add this instruction to the README.

Usage as PNG image/source object on RN 0.14 not working!

As of 0.14 release, React Native changed the way of managing images in apps. Seems it causes using icons as png don't work.

I have tested on Android device and debugging returns icon object state as
{uri: file:///path/to/file/something.png}
maybe "file:///" causes this issue?!

How to set as require() within Image component?

I would like to use the RN doc example for a bounce effect on an <Icon/>. However, the Facebook example uses an Animated.Image component. I tried setting the source to the <Icon/> but with no luck at all. Could you give an example of how to do so?
Thanks!

Assets folder not present.

Is it just me or is there anyone else too who can't find the assets folder in the path mentioned for Android Icons?

Emoticons?

It would be cool to have an emoticon set added to the project.

Crashes on Android

App is crashing after including the library,

Android 5.1
RN 0.11.4

10-03 19:37:06.549  23594-23594/io.scrollback.neighborhoods E/AndroidRuntimeFATAL EXCEPTION: main
    Process: io.scrollback.neighborhoods, PID: 23594
    com.facebook.react.bridge.UnexpectedNativeTypeException: TypeError: expected dynamic type `int64', but had type `string'
            at com.facebook.react.bridge.ReadableNativeMap.getInt(Native Method)
            at com.facebook.react.uimanager.CatalystStylesDiffMap.getInt(CatalystStylesDiffMap.java:67)
            at com.facebook.react.uimanager.BaseViewPropertyApplicator.applyCommonViewProperties(BaseViewPropertyApplicator.java:76)
            at com.facebook.react.uimanager.ViewGroupManager.updateView(ViewGroupManager.java:28)
            at com.facebook.react.views.view.ReactViewManager.updateView(ReactViewManager.java:87)
            at com.facebook.react.views.view.ReactViewManager.updateView(ReactViewManager.java:40)
            at com.facebook.react.uimanager.ViewManager.updateProperties(ViewManager.java:53)
            at com.facebook.react.uimanager.NativeViewHierarchyManager.createView(NativeViewHierarchyManager.java:182)
            at com.facebook.react.uimanager.UIViewOperationQueue$CreateViewOperation.execute(UIViewOperationQueue.java:137)
            at com.facebook.react.uimanager.UIViewOperationQueue$1.run(UIViewOperationQueue.java:574)
            at com.facebook.react.uimanager.UIViewOperationQueue$DispatchUIFrameCallback.doFrameGuarded(UIViewOperationQueue.java:622)
            at com.facebook.react.uimanager.GuardedChoreographerFrameCallback.doFrame(GuardedChoreographerFrameCallback.java:32)
            at com.facebook.react.uimanager.ReactChoreographer$ReactChoreographerDispatcher.doFrame(ReactChoreographer.java:114)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:765)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:549)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:746)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5343)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

TabBarIOS icon not centred when "title" is null or empty

I'm using this library for the icons in a TabBarIOS component in my app - works great, so thanks. One issue I'm having though is that I don't want to use the title at all (in theory, the icons are self explanatory..) however the vertical alignment of the icon is still accounting for the space which would be occupied by the title. I understand this is the default behaviour of the native component. Is there a way I can fix this?

Tabbar icon cropped

image

I've found that icon size getting here https://github.com/oblador/react-native-vector-icons/blob/master/RNVectorIconsManager/RNVectorIconsManager.m#L49 as

CGSize imageSize = CGSizeMake(fontSize, fontSize);

but it's wrong!!!

I understand that for calculating sizes of a glyph need using core text framework(https://github.com/waterlou/WTGlyphFontSet/blob/master/WTGlyphFontSet/WTGlyphFontSet.m#L137), but as temporary fix I've used

CGSize imageSize = CGSizeMake(fontSize * 1.5, fontSize);

Please add properties for rotating and flipping icons

Font Awesome offers handy properties for rotating and flipping icons:

screen shot 2015-07-16 at 1 56 52 pm

It would be great to be able to specify rotate and flip for Icon...

Rotate property example

var button = (
  <Icon name="facebook" style={styles.icon} rotate={90}>
    <Text style={styles.text}>Login with Facebook</Text>
  </Icon>
);

Flip property example

var button = (
  <Icon name="facebook" style={styles.icon} flip={'horizontal'}>
    <Text style={styles.text}>Login with Facebook</Text>
  </Icon>
);

Implementation

I think you can use transform for implementing rotate and flip.

How do you refresh an icon set

I added some icons to my icon set (I use Fontello). Unfortunately, Fontello, always changes all the references with each download. And now I'm looking at all sorts of mis renders. It seems some kind of caching issue. Any suggestions on how to refresh it?

So far I tried:

rm -rf ~/Library/Developer/Xcode/DerivedData/*
cd $TMPDIR
rm react-packager-cache-*

npm start fails after setting up react-native-vector-icons via CocoaPods

I've set up my project with the react-native-vector-icons CocoaPod as described in the README and this is what I end up with.

$ npm start

> [email protected] start /Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp
> react-native start

 ┌────────────────────────────────────────────────────────────────────────────┐
 │  Running packager on port 8081.                                            │
 │                                                                            │
 │  Keep this packager running while developing on any JS projects. Feel      │
 │  free to close this tab and run your own packager instance if you          │
 │  prefer.                                                                   │
 │                                                                            │
 │  https://github.com/facebook/react-native                                  │
 │                                                                            │
 └────────────────────────────────────────────────────────────────────────────┘
Looking for JS files in
   /Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp

[10:45:03 AM] <START> Building Dependency Graph
[10:45:03 AM] <START> Crawling File System
[10:45:03 AM] <START> Loading bundles layout
[10:45:03 AM] <END>   Loading bundles layout (0ms)

React packager ready.

[10:45:04 AM] <END>   Crawling File System (741ms)
[10:45:04 AM] <START> Building in-memory fs for JavaScript
[10:45:05 AM] <END>   Building in-memory fs for JavaScript (1535ms)
[10:45:05 AM] <START> Building Haste Map
Error building DepdendencyGraph:
 Error: Naming collision detected: /Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/ios/Pods/React/packager/react-packager/src/DependencyResolver/polyfills/Array.prototype.es6.js collides with /Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/node_modules/react-native/packager/react-packager/src/DependencyResolver/polyfills/Array.prototype.es6.js
    at HasteMap._updateHasteMap (/Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/node_modules/react-native/packager/react-packager/src/DependencyResolver/DependencyGraph/HasteMap.js:123:13)
    at /Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/node_modules/react-native/packager/react-packager/src/DependencyResolver/DependencyGraph/HasteMap.js:95:28
    at tryCallOne (/Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/node_modules/react-native/node_modules/promise/lib/core.js:37:12)
    at /Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/node_modules/react-native/node_modules/promise/lib/core.js:103:15
    at flush (/Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/node_modules/react-native/node_modules/promise/node_modules/asap/raw.js:50:29)
    at doNTCallback0 (node.js:428:9)
    at process._tickCallback (node.js:357:13)

npm ERR! Darwin 15.0.0
npm ERR! argv "/Users/jcressman/.nvm/versions/node/v5.0.0/bin/node" "/Users/jcressman/.nvm/versions/node/v5.0.0/bin/npm" "start"
npm ERR! node v5.0.0
npm ERR! npm  v2.14.11
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `react-native start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'react-native start'.
npm ERR! This is most likely a problem with the ReactNativeStrongLoopTestApp package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     react-native start
npm ERR! You can get their info via:
npm ERR!     npm owner ls ReactNativeStrongLoopTestApp
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/jcressman/Documents/Code/ReactNativeStrongLoopTestApp/npm-debug.log
$

I've created a demo repository illustrating the issue here: https://github.com/jeffcressman/react-native-vector-icons-bug-report

TabBar cannot work.

015-10-28 21:59:30.439 [error][tid:com.facebook.React.RNVectorIconsManagerQueue][RCTBatchedBridge.m:815] Exception thrown while invoking getImageForFont on target RNVectorIconsManager with params (
    Ionicons,
    "\Uf448",
    30,
    4278190080,
    11
): *** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]

errors with tabbarIOS

JSON value 'black' of type NSString cannot be converted to NSNumberreactConsoleError

4ExceptionsManager.js:87 The tab bar icon '(null)' did not match any known image or system icon

the second set of errors go away when i provide a systemIcon prop to the tab items but it doesnt seem like I can use the library

RNVerctorIconsManager error

I get an error when I'm trying to use the tabbar. There's an attached screenshot. I did add RNVectorIcons.xcodeproj to Libraries and libRNVectorIcons.a to Link Binary With Libraries under Build Phases.

How to make it work with webpack

I did all steps but once i am doing

var Icon = require('FontAwesome');
var myIcon = (<Icon name="rocket" size={30} color="#900" style={{fontSize: 20}} />);

i am getting this error:

Error: Cannot find module "FontAwesome"
 stack: 
  webpackMissingModule                           index.ios.bundle:8247
  Object.<anonymous>                             index.ios.bundle:8247
  __webpack_require__                            index.ios.bundle:1129
  Object.<anonymous>                             index.ios.bundle:1618
  __webpack_require__                            index.ios.bundle:1129
  Object.exports.default.obj.__esModule.default  index.ios.bundle:1167
  __webpack_require__                            index.ios.bundle:1129
  <unknown>                                      index.ios.bundle:1149
  <unknown>                                      index.ios.bundle:1149
  require                                        index.ios.bundle:244
 URL: undefined
 line: undefined
 message: Cannot find module "FontAwesome"

My webpack config: https://gist.github.com/artyomtrityak/55c352df5b254b33e3bc

Changing color via setNativeProps

Hi,

I'm used to changing the color of components via setNativeProps(). In this case, setNativeProps() changes the properties of the root view and not the one of the text view. I'm currently helping myself by adding:

    setNativePropsTextView(nativeProps) {
      this._text.setNativeProps(nativeProps);
    },

and

<Text ref={component => this._text = component} style={textStyle}>{glyph}</Text>

both in create-icon-set.js.

I wonder whether there is an easier way to accomplish my goal? Or if not, whether it's worth to add something like this to this module?

Regards
Philipp

[Android] icon inline does not work

var React = require('react-native')
var Icon = require('react-native-vector-icons/FontAwesome');
var {
  AppRegistry,
  Image,
  Text,
  View,
  ScrollView,
  StyleSheet,
} = React

export default React.createClass({
  render:function(){
    return (
      <View style={{flex:1,backgroundColor:'white'}}>
        <Text><Icon name="rocket" size={30} color="black"/>{'<='}Icon inlineTest</Text>

        <Icon name="rocket" size={30} color="black"/>
        <Text> {'^^^^^'}only Icon</Text>
      </View>
    )
  }
})

image

I also use the lastest react-native source code to build :-)

Issue with allowFontScaling option interfering with lineHeight

screen shot 2015-09-22 at 11 57 26 pm

When accessibility options for larger text are enabled all text sizes are increased (react native behaviour - for now allowFontScaling=true is default)

screen shot 2015-09-22 at 11 59 02 pm

So I globally set this to false for all text objects so icons and text stayed the correct size, but there is still an issue and the bottom of the icon is cut off.

screen shot 2015-09-22 at 11 56 51 pm

I have traced the issue down to this line: https://github.com/oblador/react-native-vector-icons/blob/master/lib/create-icon-set.js#L71 When this is commented out there is no issue

screen shot 2015-09-22 at 11 57 09 pm

The issue can be reproduced by creating any Text element and defining both a height and lineHeight value that are equal

<Text style={{ lineHeight: 20, height: 20, fontSize: 20}}>TEST</Text>

So is the lineHeight style necessary?

Problem installing 0.7.1 on Android

I'm trying to use the experimental 0.7.1, but got an error when building the project

  • Where:
    Build file '/Users/jrp/projects/MyApp/android/build.gradle' line: 10

  • What went wrong:
    A problem occurred evaluating root project 'MyApp'.

    Could not find method compile() for arguments [project ':react-native-vector-icons'] on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@4e94a28e.

Did I do something wrong or is there a problem with the experimental version 0.7.1 perhaps?

This is my build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'

        compile project(':react-native-vector-icons')

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
    }
}

Support for animated icons

Hi,

It's planned to have support for animated vector icons, like spinners on EvilIcons? This would be very useful to use instead of create CSS3-like animations, which sometimes has high CPU consumption.

I was reading source code, and I saw that there is using a CoreGraphics / Canvas approach, so at leat on iOS, should be possible to use Core Animation, but I'm not sure how to do that on Android.

Any suggestion about that to start to prepare a PR? :)

NavigatorIOS rightButtonIcon compatibility

Sorry for disturbing but i can not find way to integrate react-native-vector-icons with NavigatorIOS.

Code:

       import Icon from 'react-native-vector-icons/FontAwesome';
       var RefreshIcon = <Icon name='rocket' size={12} color="black" />;

       <NavigatorIOS
            style={{flex: 1}}
            initialRoute={{
              component: DashboardComponent,
              title: 'Dashboard',
              rightButtonTitle: 'Refresh',
              onRightButtonPress: DashboardComponent.refresh,
              rightButtonIcon: RefreshIcon
            }}
          />

This code does not render RefreshIcon

warning: instance method 'eventDispatcher' overrides other

This error only happens when I link the library for use with Tabbar. The build fails.
If i don't link the library, everything works

Here's the whole error:

ld: warning: instance method 'eventDispatcher' in category from /Users/isaac/Library/Developer/Xcode/DerivedData/socialapp-aehzqwedrbnqckdvgrpxjzcprgru/Build/Products/Debug-iphonesimulator/libReact.a(RCTEventDispatcher.o) overrides method from class in /Users/isaac/Library/Developer/Xcode/DerivedData/socialapp-aehzqwedrbnqckdvgrpxjzcprgru/Build/Products/Debug-iphonesimulator/libReact.a(RCTBridge.o)

NVM, this was a totally different issue

Android Support

@oblador thanks for such an awesome library. We have been using this for our iOS app and we would love to use it in the android app also. Just wondering if you are planning on supporting Android anytime in the near future? Thanks!

it not work

I want add a icon to nav leftButton, but I found that it not work.

var app = React.createClass({
getInitialState() {
return {userIcon: {}}
},
render: function() {
Icon.getImageSource('user', 20, 'red').then((source) => {
alert(source)
this.setState({ userIcon: source })
});
return (
<NavigatorIOS
style={{flex:1}}
initialRoute={{
component: Page,
leftButtonIcon: this.state.userIcon,
title: 'home',
}}
/>
);
}
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.