react-native#StyleProp TypeScript Examples

The following examples show how to use react-native#StyleProp. 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: utilities.ts    From react-native-jigsaw with MIT License 7 votes vote down vote up
/**
 * Merges a style object on top of another style object. In React Native,
 * keys with undefined values in a style object will still override styles
 * that appear earlier in a sequence. This avoids that problem.
 *
 * This lets us avoid the `...(something ? { something } : {})` pattern.
 * There doesn't seem to be a better way to do this. These all seem to not
 * work (i.e. they all result in `{ color: undefined }`:
 * `const mergedStyles = [{ color: "red" }, { color: undefined }]`
 * `const mergedStyles = StyleSheet.compose({ color: "red" }, { color: undefined })`
 * `const mergedStyles = StyleSheet.flatten([{ color: "red" }, { color: undefined }])`
 */
export function applyStyles(
  baseStyles: Array<StyleProp<any>>,
  stylesToApply: StyleProp<any> | undefined
) {
  if (!stylesToApply) {
    return;
  }

  const flattenedStyles = StyleSheet.flatten(baseStyles);

  for (const [key, value] of Object.entries(stylesToApply)) {
    if (value != null) {
      flattenedStyles[key] = value;
    }
  }

  return flattenedStyles;
}
Example #2
Source File: utilities.ts    From react-native-jigsaw with MIT License 7 votes vote down vote up
export function extractBorderAndMarginStyles(
  style: StyleProp<any>,
  additionalBorderStyles?: string[],
  additionalMarginStyles?: string[]
) {
  const flatStyle = StyleSheet.flatten(style || {});

  const borderStyles = pickBy(
    pick(flatStyle, [
      ...borderStyleNames,
      ...(additionalBorderStyles ? additionalBorderStyles : []),
    ]),
    identity
  );

  const marginStyles = pickBy(
    pick(flatStyle, [
      ...marginStyleNames,
      ...(additionalMarginStyles ? additionalMarginStyles : []),
    ]),
    identity
  );

  return { borderStyles, marginStyles };
}
Example #3
Source File: utilities.ts    From react-native-jigsaw with MIT License 7 votes vote down vote up
export function extractStyles(style: StyleProp<any>) {
  const {
    color,
    fontFamily,
    fontWeight,
    fontSize,
    lineHeight,
    letterSpacing,
    textTransform,
    textAlign,
    textDecorationLine,
    textDecorationColor,
    textDecorationStyle,
    ...viewStyles
  } = StyleSheet.flatten(style || {});

  const textStyles: TextStyle = {
    color,
    fontFamily,
    fontWeight,
    fontSize,
    lineHeight,
    letterSpacing,
    textTransform,
    textAlign,
    textDecorationLine,
    textDecorationColor,
    textDecorationStyle,
  };

  return { viewStyles, textStyles };
}
Example #4
Source File: Layout.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
export function Spacer({
  top = 8,
  right = 8,
  bottom = 8,
  left = 8,
  children,
  style,
  ...rest
}: {
  top?: number;
  right?: number;
  left?: number;
  bottom?: number;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
}) {
  return (
    <View
      style={[
        style,
        {
          paddingRight: right,
          paddingTop: top,
          paddingLeft: left,
          paddingBottom: bottom,
        },
      ]}
      {...rest}
    >
      {children}
    </View>
  );
}
Example #5
Source File: Layout.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
export function Row({
  justifyContent,
  alignItems,
  children,
  style,
  ...rest
}: {
  alignItems: ViewStyleProp.alignItems;
  justifyContent: ViewStyleProp.justifyContent;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
}) {
  return (
    <View
      style={[
        style, // style goes first b/c we can't override these
        {
          alignItems,
          flexDirection: "row",
          justifyContent: justifyContent,
        },
      ]}
      {...rest}
    >
      {children}
    </View>
  );
}
Example #6
Source File: Layout.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
export function Square({
  size = 50,
  bgColor,
  children,
  style,
  ...rest
}: {
  size: number;
  bgColor: string;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
}) {
  return (
    <Center
      style={style}
      width={size}
      height={size}
      bgColor={bgColor}
      {...rest}
    >
      {children}
    </Center>
  );
}
Example #7
Source File: Layout.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
export function Circle({
  size = 50,
  bgColor,
  children,
  style,
  ...rest
}: {
  size: number;
  bgColor: string;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
}) {
  const borderRadius = 1000;
  return (
    <Center
      width={size}
      height={size}
      bgColor={bgColor}
      style={[
        style,
        { backgroundColor: bgColor, borderRadius, overflow: "hidden" },
      ]}
      {...rest}
    >
      {children}
    </Center>
  );
}
Example #8
Source File: Layout.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
export function Center({
  width = 240,
  height = 200,
  children,
  bgColor,
  style,
  ...rest
}: {
  width: number;
  height: number;
  bgColor: string;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
}) {
  return (
    <View
      style={[
        {
          justifyContent: "center",
          alignItems: "center",
          width,
          height,
          backgroundColor: bgColor,
        },
        style,
      ]}
      {...rest}
    >
      {children}
    </View>
  );
}
Example #9
Source File: quill-editor.tsx    From react-native-cn-quill with MIT License 6 votes vote down vote up
renderWebview = (
    content: string,
    style: StyleProp<ViewStyle>,
    props: WebViewProps = {}
  ) => (
    <WebView
      scrollEnabled={false}
      hideKeyboardAccessoryView={true}
      keyboardDisplayRequiresUserAction={false}
      originWhitelist={['*']}
      style={style}
      onError={(syntheticEvent) => {
        const { nativeEvent } = syntheticEvent;
        console.warn('WebView error: ', nativeEvent);
      }}
      allowFileAccess={true}
      domStorageEnabled={false}
      automaticallyAdjustContentInsets={true}
      bounces={false}
      dataDetectorTypes="none"
      {...props}
      javaScriptEnabled={true}
      source={{ html: content }}
      ref={this._webview}
      onMessage={this.onMessage}
    />
  );
Example #10
Source File: Layout.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
export function Stack({
  children,
  justifyContent = "flex-start",
  alignItems = "flex-start",
  style,
  ...rest
}: {
  justifyContent: ViewStyleProp.justifyContent;
  alignItems: ViewStyleProp.alignItems;
  children: React.ReactNode;
  style?: StyleProp<ViewStyle>;
}) {
  return (
    // style must go first since we don't want justifyContent, alignItems overridden
    <View style={[style, { justifyContent, alignItems }]} {...rest}>
      {children}
    </View>
  );
}
Example #11
Source File: DefaultCardHeader.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 6 votes vote down vote up
function DefaultCardHeader(
  props: React.PropsWithChildren<DefaultCardHeaderProps>,
) {
  const {children, style, theme} = props;
  const headerStyle: StyleProp<ViewStyle> = [styles.cardHeader];
  if (style) {
    headerStyle.push(style);
  }
  return (
    <View
      style={[
        styles.cardHeader,
        style,
        {
          borderTopLeftRadius: theme.borderRadius,
          borderTopRightRadius: theme.borderRadius,
        },
      ]}>
      {children}
    </View>
  );
}
Example #12
Source File: Card.tsx    From nlw2-proffy with MIT License 6 votes vote down vote up
static defaultProps = {
    overlayEnabled: Platform.OS !== 'ios',
    shadowEnabled: true,
    gestureEnabled: true,
    gestureVelocityImpact: GESTURE_VELOCITY_IMPACT,
    overlay: ({
      style,
    }: {
      style: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
    }) =>
      style ? (
        <Animated.View pointerEvents="none" style={[styles.overlay, style]} />
      ) : null,
  };
Example #13
Source File: Card.d.ts    From nlw2-proffy with MIT License 6 votes vote down vote up
static defaultProps: {
        overlayEnabled: boolean;
        shadowEnabled: boolean;
        gestureEnabled: boolean;
        gestureVelocityImpact: number;
        overlay: ({ style, }: {
            style: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
        }) => JSX.Element | null;
    };
Example #14
Source File: CheckboxRow.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
renderLabel = (
  value: string | React.ReactNode,
  labelStyle: StyleProp<TextStyle>,
  textStyle: StyleProp<TextStyle>
) => {
  if (isString(value)) {
    return <Text style={[textStyle, labelStyle]}>{value}</Text>;
  } else {
    return <>{value}</>;
  }
}
Example #15
Source File: CheckboxGroupRow.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
renderLabel = (
  value: string | React.ReactNode,
  labelStyle: StyleProp<TextStyle>,
  textStyle: StyleProp<TextStyle>
) => {
  if (typeof value === "string") {
    return <Text style={[labelStyle, textStyle]}>{value}</Text>;
  } else {
    return <>{value}</>;
  }
}
Example #16
Source File: CheckboxGroup.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
CheckboxGroup: React.FC<CheckboxGroupProps> = ({
  direction = Direction.Vertical,
  values,
  onValueChange = () => {},
  style,
  children,
  ...rest
}) => {
  const _containerStyle: StyleProp<ViewStyle> = [
    {
      flexDirection: direction === Direction.Horizontal ? "row" : "column",
      overflow: "hidden",
    },
  ];

  if (direction !== Direction.Vertical) {
    _containerStyle.push({
      alignItems: "center",
    });
  }

  return (
    <View style={[{ minHeight: 40 }, style]} {...rest}>
      <Provider value={{ values, onValueChange, direction }}>
        <View style={_containerStyle}>{children}</View>
      </Provider>
    </View>
  );
}
Example #17
Source File: RadioButtonRow.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
renderLabel = (
  value: string | React.ReactNode,
  labelStyle: StyleProp<TextStyle>,
  textStyle: StyleProp<TextStyle>
) => {
  if (typeof value === "string") {
    return <Text style={[labelStyle, textStyle]}>{value}</Text>;
  } else {
    return <>{value}</>;
  }
}
Example #18
Source File: utils.ts    From react-native-controlled-mentions with MIT License 6 votes vote down vote up
defaultMentionTextStyle: StyleProp<TextStyle> = {fontWeight: 'bold', color: 'blue'}
Example #19
Source File: Avatar.tsx    From sellflow with MIT License 6 votes vote down vote up
export default function Avatar(props: Props) {
  let { firstName, lastName, size, containerStyle } = props;

  let avatarSize: StyleProp<ViewStyle> = {
    width: size,
    height: size,
    borderRadius: Math.round(size / 2),
  };
  let textSize: StyleProp<TextStyle> = {
    fontSize: Math.round(size / 2),
  };

  return (
    <View style={[styles.avatar, containerStyle, avatarSize]}>
      <Text
        style={[styles.nameInitial, textSize]}
      >{`${firstName[0]}${lastName[0]}`}</Text>
    </View>
  );
}
Example #20
Source File: index.tsx    From selftrace with MIT License 5 votes vote down vote up
PageContainer = ({
  authStatus,
  showHeader = true,
  isProtected = true,
  isFullScreen = false,
  children,
  style,
  ...rest
}: Props) => {
  // Handle isProtected case
  React.useEffect(() => {
    if (isProtected && authStatus === AuthStatus.SignedOut) {
      Router.push('/');
    }
  }, [isProtected, authStatus]);

  if (isProtected && authStatus !== AuthStatus.SignedIn) {
    return null;
  }

  // Handle isFullScreen case
  const containerStyles: StyleProp<ViewStyle> = [styles.container];

  if (isFullScreen) {
    containerStyles.push({ padding: 0 });
  }

  const Content = (
    <View style={[containerStyles, style]} {...rest}>
      {children}
    </View>
  );

  return showHeader ? (
    <>
      <Header />
      {Content}
    </>
  ) : (
    Content
  );
}
Example #21
Source File: index.tsx    From react-native-paper-toast with MIT License 5 votes vote down vote up
ToastProvider: React.FC<ToastProviderProps> = ({ children, overrides }) => {
  const initialState = useMemo(() => ({ ...defaults, ...overrides }), [overrides]);
  const [state, dispatch] = useReducer(reducer, initialState);

  const insets = useSafeAreaInsets();

  const toast = useMemo(
    () => ({
      show(options: ToastOptions) {
        const newState: ToastParams = { ...initialState, ...options, visibility: true };
        newState.position === 'bottom' && Keyboard.dismiss();
        dispatch({ type: ToastActionType.SHOW, payload: newState });
      },
      hide() {
        dispatch({ type: ToastActionType.HIDE });
      },
    }),
    [initialState]
  );

  const computedStyle = useMemo(() => {
    const base: StyleProp<ViewStyle> = {
      position: 'absolute',
      left: insets.left,
      right: insets.right,
      width: undefined,
      alignItems: 'center',
    };
    let style: StyleProp<ViewStyle>;
    if (state.position === 'bottom') {
      style = {
        ...base,
        bottom: insets.bottom,
      };
      return style;
    }
    if (state.position === 'top') {
      style = {
        ...base,
        top: insets.top,
        bottom: undefined,
      };
      return style;
    }
    style = {
      ...base,
      top: insets.top,
      bottom: insets.bottom,
      justifyContent: 'center',
    };
    return style;
  }, [insets, state.position]);

  useEffect(() => {
    dispatch({ type: ToastActionType.HYDRATE, payload: initialState });
  }, [initialState]);

  return (
    <ToastContext.Provider value={toast}>
      <Portal.Host>{children}</Portal.Host>
      <Portal>
        <Snackbar
          onDismiss={toast.hide}
          style={types[state.type]}
          wrapperStyle={computedStyle}
          duration={state.duration}
          visible={state.visibility}
          action={state.action ? { label: state.actionLabel, onPress: state.action } : undefined}
        >
          <Icon size={20} name={icons[state.type]} color="#ffffff" />
          <Text style={styles.message}>{` ${state.message}`}</Text>
        </Snackbar>
      </Portal>
    </ToastContext.Provider>
  );
}
Example #22
Source File: ProgressBar.tsx    From react-native-jigsaw with MIT License 5 votes vote down vote up
render() {
    const {
      borderColor,
      borderRadius = 4,
      borderWidth = 1,
      children,
      color = "rgba(0, 122, 255, 1)",
      style,
      unfilledColor,
      width = 150,
      ...restProps
    } = this.props;

    const innerWidth = Math.max(0, width || this.state.width) - borderWidth * 2;
    const containerStyle: StyleProp<ViewStyle> = {
      width,
      borderWidth,
      borderColor: borderColor || color,
      borderRadius,
      overflow: "hidden",
      backgroundColor: unfilledColor,
    };
    const progressStyle = {
      backgroundColor: color,
      // Always take up full height of container.
      height: "100%",
      transform: [
        {
          translateX: this.state.animationValue.interpolate({
            inputRange: [0, 1],
            outputRange: [innerWidth * -INDETERMINATE_WIDTH_FACTOR, innerWidth],
          }),
        },
        {
          translateX: this.state.progress.interpolate({
            inputRange: [0, 1],
            outputRange: [innerWidth / (I18nManager.isRTL ? 2 : -2), 0],
          }),
        },
        {
          // Interpolation a temp workaround for https://github.com/facebook/react-native/issues/6278
          scaleX: this.state.progress.interpolate({
            inputRange: [0, 1],
            outputRange: [0.0001, 1],
          }),
        },
      ],
    };

    return (
      <View
        style={[containerStyle, style]}
        onLayout={this.handleLayout}
        {...restProps}
      >
        <Animated.View style={progressStyle} />
        {children}
      </View>
    );
  }
Example #23
Source File: theme.tsx    From sellflow with MIT License 5 votes vote down vote up
defaultButton: StyleProp<ViewStyle> = {
  elevation: 0,
  height: 48,
}
Example #24
Source File: theme.tsx    From sellflow with MIT License 5 votes vote down vote up
defaultButtonLabel: StyleProp<TextStyle> = {
  fontSize: FONT_SIZE.medium,
  fontFamily: FONT_FAMILY.MEDIUM,
}
Example #25
Source File: theme.tsx    From sellflow with MIT License 5 votes vote down vote up
flatTextInputContainerStyle: StyleProp<ViewStyle> = {
  height: 75,
  marginBottom: 10,
}
Example #26
Source File: theme.tsx    From sellflow with MIT License 5 votes vote down vote up
flatTextInputStyle: StyleProp<ViewStyle> = { height: 50 }
Example #27
Source File: theme.tsx    From sellflow with MIT License 5 votes vote down vote up
outlinedTextInput: StyleProp<ViewStyle> = { height: 48 }
Example #28
Source File: theme.tsx    From sellflow with MIT License 5 votes vote down vote up
textInputLabel: StyleProp<TextStyle> = {
  fontSize: FONT_SIZE.small,
}
Example #29
Source File: Toast.tsx    From sellflow with MIT License 5 votes vote down vote up
export default function Toast(props: Props) {
  let { colors: themeColors } = useTheme();
  let { containerStyle, textStyle, data, showIcon = true } = props;
  let { isVisible, message, hideToast } = data;

  let [animatedVisibility, animatedValue] = useFadingAnimation(isVisible, {
    duration: 200,
  });

  if (!animatedVisibility) {
    return null;
  }

  return (
    <SafeAreaView pointerEvents="box-none" style={styles.wrapper}>
      <Surface
        pointerEvents="box-none"
        accessibilityLiveRegion="polite"
        style={
          [
            styles.container,
            !showIcon && styles.containerNoIcon,
            {
              opacity: animatedValue,
              transform: [
                {
                  scale: animatedValue.interpolate({
                    inputRange: [0, 1],
                    outputRange: [0.8, 1],
                  }),
                },
              ],
            },
            containerStyle,
          ] as StyleProp<ViewStyle>
        }
      >
        <Text style={[{ color: themeColors.surface }, textStyle]}>
          {message}
        </Text>
        {showIcon && hideToast && (
          <IconButton icon={'close'} color={COLORS.white} onPress={hideToast} />
        )}
      </Surface>
    </SafeAreaView>
  );
}