react-native#I18nManager JavaScript Examples
The following examples show how to use
react-native#I18nManager.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: touchable.js From rn-checkbox-list with MIT License | 6 votes |
renderRipple({ unique, progress, locationX, locationY, R }) {
let { rippleColor, rippleOpacity, rippleFades } = this.props;
let rippleStyle = {
top: locationY - radius,
[I18nManager.isRTL? 'right' : 'left']: locationX - radius,
backgroundColor: rippleColor,
transform: [{
scale: progress.interpolate({
inputRange: [0, 1],
outputRange: [0.5 / radius, R / radius],
}),
}],
opacity: rippleFades?
progress.interpolate({
inputRange: [0, 1],
outputRange: [rippleOpacity, 0],
}):
rippleOpacity,
};
return (
<Animated.View style={[styles.ripple, rippleStyle]} key={unique} />
);
}
Example #2
Source File: i18n.js From stayaway-app with European Union Public License 1.2 | 6 votes |
setupI18n = ({ languageTag, isRTL }) => {
// Allow RTL alignment in RTL languages
I18nManager.forceRTL(isRTL);
// Set i18n-js config
i18n.translations = { [languageTag]: translationGetters[languageTag]() };
i18n.locale = languageTag;
i18n.fallbacks = true;
i18n.defaultLocale = fallback.languageTag;
// Set moment js config
setMomentLocale(languageTag);
}
Example #3
Source File: constants.js From discovery-mobile-ui with MIT License | 6 votes |
RTL_DIRECTION = (rtl, style) => {
const newStyle = { ...style };
if (rtl && !I18nManager.isRTL) {
if (Object.prototype.hasOwnProperty.call(newStyle, 'flexDirection')) {
newStyle.flexDirection = newStyle.flexDirection === 'row' ? 'row-reverse' : 'row';
} else {
newStyle.flexDirection = 'row-reverse';
}
}
return newStyle;
}
Example #4
Source File: constants.js From discovery-mobile-ui with MIT License | 6 votes |
RTL_STYLE = (rtl, style) => {
const newStyle = { ...style };
if (rtl && !I18nManager.isRTL) {
Object.keys(style).foreach((key) => {
if (Object.prototype.hasOwnProperty.call(STYLE_DIRECTION_KEYS, key)) {
newStyle[STYLE_DIRECTION_KEYS[key]] = newStyle[key];
delete newStyle[key];
}
});
}
return newStyle;
}
Example #5
Source File: Input.js From react-native-select-dropdown with MIT License | 5 votes |
Input = (
{
inputStyle,
value,
valueColor,
placeholder,
placeholderTextColor,
textAlign,
onChangeText,
onEndEditing,
onSubmitEditing,
renderLeft,
renderRight,
testID,
},
ref,
) => {
const defaults = {
inputStyle: inputStyle,
value: value ?? '',
valueColor: valueColor ?? '#000000',
placeholder: placeholder ?? '',
placeholderTextColor: placeholderTextColor ?? '#CACACA',
textAlign: textAlign || (I18nManager.isRTL ? 'right' : 'left'),
onChangeText: onChangeText ?? voidFunction,
onEndEditing: onEndEditing ?? voidFunction,
onSubmitEditing: onSubmitEditing ?? voidFunction,
renderLeft: renderLeft,
renderRight: renderRight,
testID: testID,
};
const onChangeTextValidator = txt => {
if (txt.length == 1 && txt == ' ') {
return;
}
if (txt.length > 1 && txt.slice(-2) == ' ') {
return;
}
defaults.onChangeText(txt);
};
return (
<View
style={{
...styles.defaultInputStyle,
...defaults.inputStyle,
}}>
{defaults.renderLeft && <View style={styles.pressableLeft}>{defaults.renderLeft()}</View>}
<TextInput
testID={defaults.testID}
ref={ref}
value={defaults.value}
placeholder={defaults.placeholder}
placeholderTextColor={defaults.placeholderTextColor}
textAlign={defaults.textAlign}
onChangeText={onChangeTextValidator}
onEndEditing={defaults.onEndEditing}
onSubmitEditing={defaults.onSubmitEditing}
//
style={{...styles.inputField, color: defaults.valueColor}}
returnKeyType={'done'}
textContentType={'oneTimeCode'}
allowFontScaling={false}
autoComplete={'off'}
autoCorrect={false}
autoCapitalize={'none'}
autoFocus={true}
/>
{defaults.renderRight && <View style={styles.pressableRight}>{defaults.renderRight()}</View>}
</View>
);
}
Example #6
Source File: drawer.js From React-Native-Boilerplate with MIT License | 5 votes |
function Drawer(props) {
const [t, i18n] = useTranslation();
const i18 = (key) => {
return t(key);
};
// this should be called for language that need RTL for example for Arabic
const changeLanguageWithRTL = async () => {
let currentLanguage = await AsyncStorage.getItem('language');
if (currentLanguage == 'en') {
await AsyncStorage.setItem('language', 'fr');
I18nManager.forceRTL(true);
RNRestart.Restart();
} else {
await AsyncStorage.setItem('language', 'en');
I18nManager.forceRTL(false);
RNRestart.Restart();
}
};
const changeLanguageWithoutRTL = async () => {
let currentLanguage = await AsyncStorage.getItem('language');
if (currentLanguage == 'en') {
await AsyncStorage.setItem('language', 'fr');
RNRestart.Restart();
} else {
await AsyncStorage.setItem('language', 'en');
RNRestart.Restart();
}
};
return (
<SafeAreaView style={styles.container}>
<FastImage source={images.icon} style={styles.image} />
<ScrollView contentContainerStyle={styles.scrollViewContainer}>
<TouchableOpacity style={styles.itemContainer} onPress={() => changeLanguageWithRTL()}>
{drawerIcons.language}
<Text style={styles.itemText}>{i18('Drawer.changeLanguage')}</Text>
</TouchableOpacity>
</ScrollView>
</SafeAreaView>
);
}
Example #7
Source File: SelectDropdown.js From react-native-select-dropdown with MIT License | 4 votes |
SelectDropdown = (
{
data /* array */,
onSelect /* function */,
defaultButtonText /* String */,
buttonTextAfterSelection /* function */,
rowTextForSelection /* function */,
defaultValue /* any */,
defaultValueByIndex /* integer */,
disabled /* boolean */,
disableAutoScroll /* boolean */,
onFocus /* function */,
onBlur /* function */,
/////////////////////////////
buttonStyle /* style object for button */,
buttonTextStyle /* style object for button text */,
renderCustomizedButtonChild /* function returns React component for customized button */,
/////////////////////////////
renderDropdownIcon,
dropdownIconPosition,
statusBarTranslucent,
dropdownStyle,
dropdownOverlayColor /* string */,
/////////////////////////////
rowStyle /* style object for row */,
rowTextStyle /* style object for row text */,
selectedRowStyle /* style object for selected row */,
selectedRowTextStyle /* style object for selected row text */,
renderCustomizedRowChild /* function returns React component for customized row */,
/////////////////////////////
search /* boolean */,
searchInputStyle /* style object for search input */,
searchInputTxtColor /* text color for search input */,
searchPlaceHolder /* placeholder text for search input */,
searchPlaceHolderColor /* text color for search input placeholder */,
renderSearchInputLeftIcon /* function returns React component for search input icon */,
renderSearchInputRightIcon /* function returns React component for search input icon */,
},
ref,
) => {
///////////////////////////////////////////////////////
useImperativeHandle(ref, () => ({
reset: () => {
reset();
},
openDropdown: () => {
openDropdown();
},
closeDropdown: () => {
closeDropdown();
},
}));
///////////////////////////////////////////////////////
const DropdownButton = useRef(); // button ref to get positions
const [isVisible, setIsVisible] = useState(false); // dropdown visible ?
const [buttonLayout, setButtonLayout] = useState(null);
const [dropdownPX, setDropdownPX] = useState(0); // position x
const [dropdownPY, setDropdownPY] = useState(0); // position y
const [dropdownHEIGHT, setDropdownHEIGHT] = useState(() => {
return calculateDropdownHeight(dropdownStyle, rowStyle, data?.length || 0, search);
}); // dropdown height
const [dropdownWIDTH, setDropdownWIDTH] = useState(0); // dropdown width
///////////////////////////////////////////////////////
const [selectedItem, setSelectedItem] = useState(null); // selected item from dropdown
const [selectedIndex, setSelectedIndex] = useState(-1); // index of selected item from dropdown
const dropDownFlatlistRef = useRef(null); // ref to the drop down flatlist
///////////////////////////////////////////////////////
const [searchTxt, setSearchTxt] = useState('');
const keyboardHeight = useKeyboardHeight();
const remainigHeightAvoidKeyboard = height - keyboardHeight;
const safeDropdownViewUnderKeyboard = rowStyle && rowStyle.height ? rowStyle.height * 3 : 50 * 3;
/* ******************* useEffect ******************* */
// data array changes
useEffect(() => {
if (!data || data.length == 0) {
reset();
}
}, [data]);
// default value by index added or changed
useEffect(() => {
// defaultValueByIndex may be equals zero
if (isExist(defaultValueByIndex)) {
if (data && isExist(data[defaultValueByIndex])) {
setDefault(defaultValueByIndex);
}
}
}, [defaultValueByIndex]);
// default value added or changed
useEffect(() => {
// defaultValue may be equals zero
if (isExist(defaultValue)) {
if (data && findIndexInArr(defaultValue, data) >= 0) {
setDefault(findIndexInArr(defaultValue, data));
}
}
}, [defaultValue]);
// for height changes
useEffect(() => {
setDropdownHEIGHT(calculateDropdownHeight(dropdownStyle, rowStyle, data?.length || 0, search));
}, [dropdownStyle, rowStyle, data]);
///////////////////////////////////////////////////////
/* ******************** Methods ******************** */
const openDropdown = () => {
DropdownButton.current.measure((fx, fy, w, h, px, py) => {
// console.log('position y => ', py, '\nheight', h, '\nposition x => ', px)
setButtonLayout({w, h, px, py});
if (height - 18 < py + h + dropdownHEIGHT) {
setDropdownPX(px);
setDropdownPY(py - 2 - dropdownHEIGHT);
} else {
setDropdownPX(px);
setDropdownPY(py + h + 2);
}
setDropdownWIDTH(dropdownStyle?.width || w);
setIsVisible(true);
onFocus && onFocus();
});
};
const closeDropdown = () => {
setIsVisible(false);
setSearchTxt('');
onBlur && onBlur();
};
const reset = () => {
setSelectedItem(null);
setSelectedIndex(-1);
setSearchTxt('');
};
const setDefault = index => {
setSelectedItem(data[index]);
setSelectedIndex(index);
};
const getItemLayout = (data, index) => ({
index,
length: data?.length || 0,
offset: rowStyle && rowStyle.height ? rowStyle.height * index : 50 * index,
});
const onLayout = () => {
if (disableAutoScroll) {
return;
}
if (selectedIndex >= 3 && dropDownFlatlistRef) {
dropDownFlatlistRef.current.scrollToOffset({
offset: rowStyle && rowStyle.height ? rowStyle.height * selectedIndex : 50 * selectedIndex,
animated: true,
});
}
};
const onSelectItem = (item, index) => {
closeDropdown();
onSelect(item, index);
setSelectedItem(item);
setSelectedIndex(index);
};
///////////////////////////////////////////////////////
/* ******************** Render Methods ******************** */
const renderSearchView = () => {
return (
search && (
<View style={{...styles.searchViewStyle, ...{width: buttonLayout.w}}}>
<Input
value={searchTxt}
valueColor={searchInputTxtColor}
placeholder={searchPlaceHolder}
placeholderTextColor={searchPlaceHolderColor}
onChangeText={setSearchTxt}
inputStyle={searchInputStyle}
renderLeft={renderSearchInputLeftIcon}
renderRight={renderSearchInputRightIcon}
/>
</View>
)
);
};
const renderFlatlistItem = ({item, index}) => {
return item ? (
<TouchableOpacity
activeOpacity={0.8}
style={{...styles.dropdownRow, ...rowStyle, ...(index == selectedIndex && selectedRowStyle)}}
onPress={() => onSelectItem(item, index)}>
{renderCustomizedRowChild ? (
<View style={styles.dropdownCustomizedRowParent}>{renderCustomizedRowChild(item, index)}</View>
) : (
<Text
numberOfLines={1}
allowFontScaling={false}
style={{...styles.dropdownRowText, ...rowTextStyle, ...(index == selectedIndex && selectedRowTextStyle)}}>
{rowTextForSelection ? rowTextForSelection(item, index) : item.toString()}
</Text>
)}
</TouchableOpacity>
) : (
<></>
);
};
const renderDropdown = () => {
return (
isVisible && (
<Modal
supportedOrientations={['portrait', 'landscape']}
animationType="none"
transparent={true}
statusBarTranslucent={statusBarTranslucent || false}
visible={isVisible}>
<TouchableOpacity
activeOpacity={1}
onPress={() => closeDropdown()}
style={{
...styles.dropdownOverlay,
...(dropdownOverlayColor && {
backgroundColor: dropdownOverlayColor,
}),
}}
/>
<View
style={{
...styles.dropdownOverlayView,
...styles.shadow,
...dropdownStyle,
...{
position: 'absolute',
top:
remainigHeightAvoidKeyboard < dropdownPY + safeDropdownViewUnderKeyboard
? remainigHeightAvoidKeyboard - safeDropdownViewUnderKeyboard
: dropdownPY,
height: dropdownHEIGHT,
width: dropdownWIDTH,
borderTopWidth: 0,
overflow: 'hidden',
},
...(I18nManager.isRTL
? {right: dropdownStyle?.right || dropdownPX}
: {left: dropdownStyle?.left || dropdownPX}),
}}>
{!data || data.length == 0 ? (
<View style={styles.dropdownActivityIndicatorView}>
<ActivityIndicator size="small" color={'#999999'} />
</View>
) : (
<FlatList
data={searchTxt ? deepSearchInArr(searchTxt, data) : data}
keyExtractor={(item, index) => index.toString()}
ref={ref => (dropDownFlatlistRef.current = ref)}
renderItem={renderFlatlistItem}
getItemLayout={getItemLayout}
onLayout={onLayout}
ListHeaderComponent={renderSearchView()}
stickyHeaderIndices={search && [0]}
keyboardShouldPersistTaps="always"
/>
)}
</View>
</Modal>
)
);
};
///////////////////////////////////////////////////////
return (
<TouchableOpacity
ref={DropdownButton}
disabled={disabled}
activeOpacity={0.8}
style={{
...styles.dropdownButton,
...(dropdownIconPosition == 'left' ? {flexDirection: 'row'} : {flexDirection: 'row-reverse'}),
...buttonStyle,
}}
onPress={openDropdown}>
{renderDropdown()}
{renderDropdownIcon && renderDropdownIcon(isVisible)}
{renderCustomizedButtonChild ? (
<View style={styles.dropdownCustomizedButtonParent}>
{renderCustomizedButtonChild(selectedItem, selectedIndex)}
</View>
) : (
<Text numberOfLines={1} allowFontScaling={false} style={{...styles.dropdownButtonText, ...buttonTextStyle}}>
{isExist(selectedItem)
? buttonTextAfterSelection
? buttonTextAfterSelection(selectedItem, selectedIndex)
: selectedItem.toString()
: defaultButtonText || 'Select an option.'}
</Text>
)}
</TouchableOpacity>
);
}
Example #8
Source File: Menu.js From react-native-beauty-webview with MIT License | 4 votes |
render() {
const { isRTL } = I18nManager;
const dimensions = Dimensions.get('window');
const { width: windowWidth } = dimensions;
const windowHeight = dimensions.height - (StatusBar.currentHeight || 0);
const {
menuSizeAnimation,
menuWidth,
menuHeight,
buttonWidth,
buttonHeight,
opacityAnimation,
} = this.state;
const menuSize = {
width: menuSizeAnimation.x,
height: menuSizeAnimation.y,
};
// Adjust position of menu
let { left, top } = this.state;
const transforms = [];
if (
(isRTL && left + buttonWidth - menuWidth > SCREEN_INDENT) ||
(!isRTL && left + menuWidth > windowWidth - SCREEN_INDENT)
) {
transforms.push({
translateX: Animated.multiply(menuSizeAnimation.x, -1),
});
left = Math.min(windowWidth - SCREEN_INDENT, left + buttonWidth);
} else if (left < SCREEN_INDENT) {
left = SCREEN_INDENT;
}
// Flip by Y axis if menu hits bottom screen border
if (top > windowHeight - menuHeight - SCREEN_INDENT) {
transforms.push({
translateY: Animated.multiply(menuSizeAnimation.y, -1),
});
top = windowHeight - SCREEN_INDENT;
top = Math.min(windowHeight - SCREEN_INDENT, top + buttonHeight);
} else if (top < SCREEN_INDENT) {
top = SCREEN_INDENT;
}
const shadowMenuContainerStyle = {
opacity: opacityAnimation,
transform: transforms,
top,
// Switch left to right for rtl devices
...(isRTL ? { right: left } : { left }),
};
const { menuState } = this.state;
const animationStarted = menuState === STATES.ANIMATING;
const modalVisible = menuState === STATES.SHOWN || animationStarted;
const { testID, button, style, children } = this.props;
return (
<View ref={this._setContainerRef} collapsable={false} testID={testID}>
<View>{button}</View>
<Modal
visible={modalVisible}
onRequestClose={this._hide}
supportedOrientations={[
'portrait',
'portrait-upside-down',
'landscape',
'landscape-left',
'landscape-right',
]}
transparent
onDismiss={this._onDismiss}
>
<TouchableWithoutFeedback onPress={this._hide} accessible={false}>
<View style={StyleSheet.absoluteFill}>
<Animated.View
onLayout={this._onMenuLayout}
style={[
styles.shadowMenuContainer,
shadowMenuContainerStyle,
style,
]}
>
<Animated.View
style={[styles.menuContainer, animationStarted && menuSize]}
>
{children}
</Animated.View>
</Animated.View>
</View>
</TouchableWithoutFeedback>
</Modal>
</View>
);
}