Skip to content

Instantly share code, notes, and snippets.

@AliAkhgar
Last active September 5, 2022 19:21
Show Gist options
  • Save AliAkhgar/c5e438d3a2255b0f1a77f3344b13eed3 to your computer and use it in GitHub Desktop.
Save AliAkhgar/c5e438d3a2255b0f1a77f3344b13eed3 to your computer and use it in GitHub Desktop.
Quick Custom Font-Icon ReactNative | Just include font in assets | Extracted from react-native-vector-icons
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Platform, Text } from 'react-native';
export const DEFAULT_ICON_SIZE = 12;
export const DEFAULT_ICON_COLOR = 'black';
export default function createIconSet(glyphMap, fontFamily, fontFile, fontStyle) {
// Android doesn't care about actual fontFamily name, it will only look in fonts folder.
const fontBasename = fontFile ? fontFile.replace(/\.(otf|ttf)$/, '') : fontFamily;
const fontReference = Platform.select({
windows: `/Assets/${fontFile}#${fontFamily}`,
android: fontBasename,
web: fontBasename,
default: fontFamily,
});
const IconNamePropType = PropTypes.oneOf(Object.keys(glyphMap));
class Icon extends PureComponent {
root = null;
static propTypes = {
allowFontScaling: PropTypes.bool,
name: IconNamePropType,
size: PropTypes.number,
color: PropTypes.any, // eslint-disable-line react/forbid-prop-types
children: PropTypes.node,
style: PropTypes.any, // eslint-disable-line react/forbid-prop-types
};
static defaultProps = {
size: DEFAULT_ICON_SIZE,
allowFontScaling: false,
};
setNativeProps(nativeProps) {
if (this.root) {
this.root.setNativeProps(nativeProps);
}
}
handleRef = (ref) => {
this.root = ref;
};
render() {
const { name, size, color, style, children, ...props } = this.props;
let glyph = name ? glyphMap[name] || '?' : '';
if (typeof glyph === 'number') {
glyph = String.fromCodePoint(glyph);
}
const styleDefaults = {
fontSize: size,
color,
};
const styleOverrides = {
fontFamily: fontReference,
fontWeight: 'normal',
fontStyle: 'normal',
};
props.style = [styleDefaults, style, styleOverrides, fontStyle || {}];
props.ref = this.handleRef;
return (
<Text selectable={false} {...props}>
{glyph}
{children}
</Text>
);
}
}
function hasIcon(name) {
return Object.prototype.hasOwnProperty.call(glyphMap, name);
}
function getRawGlyphMap() {
return glyphMap;
}
function getFontFamily() {
return fontReference;
}
Icon.hasIcon = hasIcon;
Icon.getRawGlyphMap = getRawGlyphMap;
Icon.getFontFamily = getFontFamily;
return Icon;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment