react-native#TextInput TypeScript Examples

The following examples show how to use react-native#TextInput. 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: MyTextInput.tsx    From vsinder with Apache License 2.0 7 votes vote down vote up
MyTextInput: React.FC<TextInputProps> = ({
  style,
  onFocus,
  onBlur,
  ...props
}) => {
  const [showBorder, setShowBorder] = useState(false);
  const [
    { inputBackground, inputOptionActiveBorder, inputForeground },
  ] = useContext(ThemeContext);
  return (
    <TextInput
      {...props}
      onBlur={(e) => {
        setShowBorder(false);
        onBlur?.(e);
      }}
      underlineColorAndroid="transparent"
      onFocus={(e) => {
        setShowBorder(true);
        onFocus?.(e);
      }}
      style={[
        {
          paddingVertical: 8,
          paddingHorizontal: 6,
          fontSize: 16,
          color: inputForeground,
          backgroundColor: inputBackground,
          borderColor: showBorder ? inputOptionActiveBorder : "transparent",
          borderWidth: 1,
        },
        style,
      ]}
    />
  );
}
Example #2
Source File: Input.tsx    From react-native-meetio with MIT License 6 votes vote down vote up
Input = React.forwardRef<TextInput, Props>(
  ({ inputProps, ...rest }, ref) => {
    const props = useRestyle(restyleFunctions, rest);
    const theme = useTheme<Theme>();

    return (
      <Box backgroundColor="white" {...props}>
        <TextInput
          ref={ref}
          selectionColor={theme.colors.lightPink}
          {...inputProps}
        />
      </Box>
    );
  }
)
Example #3
Source File: index.tsx    From frontatish with MIT License 6 votes vote down vote up
render() {
    const {
      label,
      error,
      containerStyle,
      labelStyle,
      Colors,
      disabled,
      disabledTextStyle,
      inputTextStyle,
    } = this.props;
    styles = getStyles(Colors);
    const bottomBorderStyles = this.getBottomBorderStyles();
    const textInputStyle = disabled
      ? { ...styles.disabledTextStyle, ...disabledTextStyle }
      : { ...styles.inputTextStyle, ...inputTextStyle };
    return (
      <TouchableWithoutFeedback onPress={this.setFocus}>
        <View style={[styles.containerStyle, containerStyle]}>
          <Text style={[styles.lableStyle, labelStyle]}>{label}</Text>
          <TextInput
            {...this.props}
            style={textInputStyle}
            // eslint-disable-next-line no-return-assign
            ref={this.textInput}
            editable={!disabled}
            onFocus={() => this.setActive(true)}
            onBlur={() => this.setActive(false)}
          />
          <View style={bottomBorderStyles} />
          {error && <Text style={styles.errorStyle}>{error}</Text>}
        </View>
      </TouchableWithoutFeedback>
    );
  }
Example #4
Source File: RequestDetails.tsx    From react-native-network-logger with MIT License 6 votes vote down vote up
LargeText: React.FC<{ children: string }> = ({ children }) => {
  const styles = useThemedStyles(themedStyles);

  if (Platform.OS === 'ios') {
    /**
     * A readonly TextInput is used because large Text blocks sometimes don't render on iOS
     * See this issue https://github.com/facebook/react-native/issues/19453
     * Note: Even with the fix mentioned in the comments, text with ~10,000 lines still fails to render
     */
    return (
      <TextInput
        style={[styles.content, styles.largeContent]}
        multiline
        editable={false}
      >
        {children}
      </TextInput>
    );
  }

  return (
    <View style={styles.largeContent}>
      <ScrollView nestedScrollEnabled>
        <View>
          <Text style={styles.content}>{children}</Text>
        </View>
      </ScrollView>
    </View>
  );
}
Example #5
Source File: KnobBubble.tsx    From react-native-range-slider-expo with MIT License 6 votes vote down vote up
KnobBubble = ({ translateX, scale, knobSize, valueLabelsBackgroundColor: fill, textStyle, textInputRef }: KnobProps) => {
  const d = useMemo(() => "M20.368027196163986,55.24077513402203 C20.368027196163986,55.00364778429386 37.12897994729114,42.11537830086061 39.19501224411266,22.754628132990383 C41.26104454093417,3.393877965120147 24.647119286738516,0.571820003300814 20.368027196163986,0.7019902620266703 C16.088935105589453,0.8321519518460209 -0.40167016290734386,3.5393865664909434 0.7742997013327574,21.806127302984205 C1.950269565572857,40.07286803947746 20.368027196163986,55.4779024837502 20.368027196163986,55.24077513402203 z", []);
  const stroke = fill;
  const height = 56;
  const svgOffset = useMemo(() => osRtl ? { right: (knobSize - 40) / 2 } : { left: (knobSize - 40) / 2 }, [knobSize]);
  return (
    <Animated.View
      style={[styles.container, { opacity: scale, transform: [{ translateX }, { translateY: height / 2 }, { scale }, { translateY: -height / 2 },] }]}
    >
      <Svg width={height * .74} height={height} style={[svgOffset, { justifyContent: 'center', alignItems: 'center' }]} >
        <Path {...{ d, fill, stroke }} strokeWidth={1} />
      </Svg>
      <TextInput editable={false} style={[styles.textInput, svgOffset, textStyle]} ref={textInputRef} />
    </Animated.View>
  )
}
Example #6
Source File: index.tsx    From rn-formly with MIT License 6 votes vote down vote up
InputText = ({
  value,
  textInputStyle,
  defaultColor,
  upsideEmit,
  ...rest
}: TextInputProps) => {
  const onChangeHandler = (text: string) => {
    upsideEmit(text);
    return;
  };
  return (
    <>
      <TextInput
        style={[
          { color: defaultColor, borderColor: defaultColor },
          styles.defaultTextInputStyle,
          textInputStyle,
        ]}
        onChangeText={(text) => onChangeHandler(text)}
        value={value}
        {...rest}
      />
    </>
  );
}
Example #7
Source File: CardRowTextInput.tsx    From react-native-ios-context-menu with MIT License 6 votes vote down vote up
render(){
    const props = this.props;

    return(
      <TextInput
        style={styles.cardRowTextInput}
        onChangeText={this._handleOnChangeText}
        placeholder={props.placeholder}
        placeholderTextColor={Colors.INDIGO[300]}
      />
    );
  }
Example #8
Source File: SingleNumberInput.tsx    From react-native-crypto-wallet-app with MIT License 6 votes vote down vote up
SingleNumberInput = forwardRef<TextInput, ISingleNumberInputProps>(
  ({ name, value, onChangeText }, ref) => {
    const [isFocused, setIsFocused] = useState<boolean>(false);

    return (
      <Input
        {...{ value, ref }}
        onChangeText={text => onChangeText(text, name)}
        borderColor={isFocused ? 'inputActive' : 'inputInactive'}
        borderWidth={2}
        borderRadius="s"
        width={58}
        height={58}
        textAlign="center"
        textAlignVertical="center"
        fontSize={30}
        fontFamily="TitilliumWeb-Regular"
        color="inputActive"
        onFocus={() => setIsFocused(true)}
        onBlur={() => setIsFocused(false)}
        maxLength={1}
        keyboardType="numeric"
        style={SingleNumberInputStyle.container}
      />
    );
  },
)
Example #9
Source File: KeyboardManager.tsx    From nlw2-proffy with MIT License 6 votes vote down vote up
private handlePageChangeStart = () => {
    if (!this.props.enabled) {
      return;
    }

    this.clearKeyboardTimeout();

    // @ts-expect-error: currentlyFocusedInput is pretty new, so not in the type definitions
    const input = TextInput.State.currentlyFocusedInput
      ? // @ts-expect-error
        TextInput.State.currentlyFocusedInput()
      : TextInput.State.currentlyFocusedField();

    // When a page change begins, blur the currently focused input
    TextInput.State.blurTextInput(input);

    // Store the id of this input so we can refocus it if change was cancelled
    this.previouslyFocusedTextInput = input;

    // Store timestamp for touch start
    this.startTimestamp = Date.now();
  };
Example #10
Source File: CustomTextInput.tsx    From react-native-chatapp-socket with MIT License 6 votes vote down vote up
CustomTextInput = (props: CustomTextInputProps) => {
    return (
        <TextInput
            placeholder={props.placeholder}
            onChangeText={props.onChangeText}
            secureTextEntry={props.secureTextEntry}
            style={styles.input}
            placeholderTextColor={SECONDARY_DARK_COLOR}
            value={props.value}
        />
    );

}
Example #11
Source File: SearchBar.tsx    From lexicon with MIT License 6 votes vote down vote up
export function SearchBar(props: Props) {
  const styles = useStyles();
  const { colors } = useTheme();

  const { searchValue, onSearchValueChange, style, ...otherProps } = props;

  return (
    <View style={[styles.searchContainer, style]} {...otherProps}>
      <Icon name="Search" color={colors.textLighter} />
      <TextInput
        style={styles.searchTextInput}
        value={searchValue}
        onChangeText={(value) => onSearchValueChange(value)}
        placeholder={t('Search for relevant tags ...')}
        placeholderTextColor={colors.textLighter}
        autoCorrect={false}
      />
      {searchValue !== '' && (
        <Icon
          name="Cancel"
          color={colors.textLighter}
          onPress={() => onSearchValueChange('')}
        />
      )}
    </View>
  );
}
Example #12
Source File: index.tsx    From krmanga with MIT License 6 votes vote down vote up
function Input({ field, form, iconName, cancel, ...rest }: IProps) {

    const onPress = () => {
        if (typeof cancel === "function") {
            cancel(form, field);
        }

    };

    return (
        <View style={styles.container}>
            <View style={styles.inputView}>
                <Icon name={iconName} color={Color.night} size={20} />
                <TextInput
                    {...field}
                    {...rest}
                    style={styles.input}
                    onChangeText={form.handleChange(field.name)}
                    onBlur={form.handleBlur(field.name)}
                />
                <Touchable onPress={onPress}>
                    <Icon name={"icon-chacha"} color={Color.night} size={20} />
                </Touchable>
                <ErrorMessage
                    name={field.name}
                    component={Text}
                    render={
                        msg => {
                            return (
                                <Text style={styles.error}>{msg}</Text>
                            );
                        }
                    }
                />
            </View>
        </View>
    );
}
Example #13
Source File: CardInput.tsx    From react-native-credit-card-form-ui with MIT License 6 votes vote down vote up
CardInput: any = ({
  name,
  maskProps,
  refInput,
  onChange = () => {},
  style,
  ...props
}: CardInputProps) => {
  const handleChange = React.useCallback(
    (text) => {
      const value = text.toUpperCase();
      return onChange(name, value);
    },
    [name, onChange]
  );

  const setRef = (inputRef: any, ref: any) => {
    if (typeof ref === 'object') {
      ref.current = inputRef;
    }
  };

  const InputComponent: any = maskProps ? TextInputMask : TextInput;
  const customProps = maskProps
    ? { refInput: (ref: any) => setRef(ref, refInput) }
    : { ref: refInput };

  return (
    <InputComponent
      style={style}
      onChangeText={handleChange}
      hitSlop={{ top: 10, bottom: 10, left: 0, right: 0 }}
      {...maskProps}
      {...props}
      {...customProps}
    />
  );
}
Example #14
Source File: DefaultTextInput.tsx    From orangehrm-os-mobile with GNU General Public License v3.0 6 votes vote down vote up
DefaultTextInput = React.forwardRef<
  TextInput,
  React.PropsWithChildren<TextInputProps>
>((props, ref) => {
  const {viewProps, ...inputProps} = props;
  const theme = useTheme();
  return (
    <View {...viewProps}>
      <TextInput
        ref={ref}
        {...inputProps}
        style={[
          {
            fontSize: theme.typography.fontSize,
            color: theme.typography.primaryColor,
          },
          inputProps.style,
        ]}
      />
    </View>
  );
})
Example #15
Source File: index.tsx    From lets-fork-native with MIT License 6 votes vote down vote up
export default function Input(props: Props): React.ReactElement {
  const {
    handleChange, keyboardType, placeholder, value,
  } = props

  return (
    <TextInput
      onChangeText={handleChange}
      style={styles.input}
      value={value}
      placeholder={placeholder}
      keyboardType={keyboardType}
    />
  )
}
Example #16
Source File: FakeCurrencyInput.tsx    From react-native-currency-input with MIT License 5 votes vote down vote up
FakeCurrencyInput = React.forwardRef<TextInput, FakeCurrencyInputProps>(
  (props, ref) => {
    const {
      value,
      style,
      onChangeText,
      containerStyle,
      caretHidden,
      caretColor,
      selectionColor,
      onFocus,
      onBlur,
      ...rest
    } = props;

    const [focused, setFocused] = React.useState(false);
    const [formattedValue, setFormattedValue] = React.useState('');

    return (
      <View style={[containerStyle, styles.inputContainer]}>
        <TextWithCursor
          style={style}
          cursorVisible={focused && !caretHidden}
          cursorProps={{ style: { color: caretColor || selectionColor } }}
        >
          {formattedValue}
        </TextWithCursor>
        <CurrencyInput
          value={value}
          onChangeText={(text) => {
            setFormattedValue(text);
            onChangeText && onChangeText(text);
          }}
          {...rest}
          selectionColor="transparent"
          caretHidden
          onFocus={(e) => {
            setFocused(true);
            onFocus && onFocus(e);
          }}
          onBlur={(e) => {
            setFocused(false);
            onBlur && onBlur(e);
          }}
          style={styles.inputHidden}
          ref={ref}
        />
      </View>
    );
  }
)
Example #17
Source File: CodeInput.tsx    From mobile with Apache License 2.0 5 votes vote down vote up
CodeInput = ({value, onChange, accessibilityLabel}: CodeInputProps) => {
  const inputRef = useRef<TextInput>(null);
  const onChangeTrimmed = useCallback(text => onChange(text.trim()), [onChange]);

  const displayValue = useCallback(
    () =>
      Array(8)
        .fill(null)
        .map((_, x) => {
          const characterToDisplay = value[x] || ' ';
          return (
            <Box
              /* eslint-disable-next-line react/no-array-index-key */
              key={`input-${x}`}
              flex={1}
              marginHorizontal="xs"
              borderBottomWidth={1.5}
              borderBottomColor={inputBorderColor(value, x)}
            >
              <Text variant="codeInput" color="overlayBodyText" textAlign="center" marginBottom="s">
                {characterToDisplay}
              </Text>
            </Box>
          );
        }),
    [value],
  );

  const giveFocus = useCallback(() => inputRef.current?.focus(), []);

  return (
    <>
      <TextInput
        value={value}
        ref={inputRef}
        onChangeText={onChangeTrimmed}
        keyboardType="number-pad"
        autoCorrect={false}
        autoCompleteType="off"
        returnKeyType="done"
        accessibilityLabel={accessibilityLabel}
        caretHidden
        maxLength={8}
        style={styles.input}
      />
      <TouchableWithoutFeedback
        onPress={giveFocus}
        accessibilityElementsHidden
        importantForAccessibility="no-hide-descendants"
      >
        <Box flexDirection="row" justifyContent="space-evenly" marginHorizontal="m" paddingVertical="l">
          {displayValue()}
        </Box>
      </TouchableWithoutFeedback>
    </>
  );
}
Example #18
Source File: index.tsx    From NLW-1.0 with MIT License 5 votes vote down vote up
Home: React.FC = () => {
  const [uf, setUf] = useState("");
  const [city, setCity] = useState("");

  const navigation = useNavigation();

  function handleNavigateToPoints() {
    navigation.navigate("Points", {
      uf,
      city,
    });
  }

  return (
    <KeyboardAvoidingView
      style={{ flex: 1 }}
      behavior={Platform.OS === "ios" ? "padding" : undefined}
    >
      <ImageBackground
        source={require("../../assets/home-background.png")}
        style={styles.container}
        imageStyle={{
          width: 274,
          height: 368,
        }}
      >
        <View style={styles.main}>
          <Image source={require("../../assets/logo.png")} />
          <View>
            <Text style={styles.title}>
              Seu marketplace de coleta de resíduos
            </Text>
            <Text style={styles.description}>
              Ajudamos pessoas a encontrarem pontos de coleta de forma
              eficiente.
            </Text>
          </View>
        </View>
        <View style={styles.footer}>
          <TextInput
            style={styles.input}
            value={uf}
            onChangeText={setUf}
            maxLength={2}
            autoCapitalize="characters"
            autoCorrect={false}
            placeholder="Digite a UF"
          />
          <TextInput
            style={styles.input}
            placeholder="Digite a cidade"
            value={city}
            autoCorrect={false}
            onChangeText={setCity}
          />
          <RectButton
            style={styles.button}
            onPress={() => handleNavigateToPoints()}
          >
            <View style={styles.buttonIcon}>
              <Icon name="arrow-right" color="#fff" size={24} />
            </View>
            <Text style={styles.buttonText}>Entrar</Text>
          </RectButton>
        </View>
      </ImageBackground>
    </KeyboardAvoidingView>
  );
}
Example #19
Source File: index.tsx    From frontatish with MIT License 5 votes vote down vote up
textInput: React.RefObject<TextInput>;
Example #20
Source File: Login.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
render() {
    return (
      <KeyboardAvoidingView style={styles.container} behavior='padding'>
          <View style={styles.header}>
            <Text style={styles.header_title}><%=project.name%></Text>
            <Text style={styles.header_subTitle}>Sign in to your account</Text>
          </View>
          <View style={styles.form}>
            {this.badCredentialsError && (
              <Text style={styles.form_globalError}>
                Login failed. Unknown login or bad password.
              </Text>
            )}
            {this.serverError && (
              <Text style={styles.form_globalError}>Server error</Text>
            )}
            <TextInput style={[
                styles.form_input,
                this.badCredentialsError && styles.form_input__invalid
              ]}
              value={this.login}
              placeholder="Login"
              placeholderTextColor={colors.placeholders}
              onChangeText={this.onLoginChange}
              onSubmitEditing={this.onSubmit}
            />
            <TextInput style={[
                styles.form_input,
                this.badCredentialsError && styles.form_input__invalid
              ]}
              value={this.password}
              placeholder="Password"
              placeholderTextColor={colors.placeholders}
              secureTextEntry={true}
              onChangeText={this.onPasswordChange}
              onSubmitEditing={this.onSubmit}
            />
            <PrimaryButton onPress={this.onSubmit}
                           loading={this.loading}
                           style={styles.form_submitButton}
                           disabled={!this.isSubmitEnabled()}
            >
              Log in
            </PrimaryButton>
          </View>
      </KeyboardAvoidingView>
    );
  }
Example #21
Source File: TextInput.tsx    From companion-kit with MIT License 5 votes vote down vote up
render() {
        const {
            model,
            styleInput,
            styleWrap,
            styleError,
            styleLabel,
            placeholder,
            secureTextEntry,
            placeholderTextColor,
            forceError,
            editable,
            onTouchStart,
            value,
            label,
            multiline,
            numberOfLines,
            returnKeyType,
            inputRef,
            autoFocus,
            autoCompleteType,
            keyboardType,
            autoCorrect,
            autoCapitalize,
            textContentType,
            skipBlurOnSubmit,
        } = this.props;

        const errorText = model?.error || forceError;

        return (
            <View style={[styles.wrap, styleWrap]}>
                <TextInput
                    autoCorrect={autoCorrect}
                    ref={inputRef}
                    onSubmitEditing={this._onSubmit}
                    returnKeyType={returnKeyType || 'done'}
                    onChangeText={this._onChange}
                    value={model?.value || value}
                    onFocus={this._onFocus}
                    onBlur={this._onBlur}
                    placeholder={placeholder}
                    blurOnSubmit={!skipBlurOnSubmit}
                    autoCapitalize={autoCapitalize}
                    multiline={multiline}
                    autoFocus={autoFocus}
                    autoCompleteType={autoCompleteType}
                    keyboardType={keyboardType}
                    numberOfLines={numberOfLines}
                    placeholderTextColor={placeholderTextColor || Colors.inputPlaceholder}
                    style={[
                        styles.default,
                        TextStyles.h2,
                        { color: Colors.inputText },
                        styleInput,
                    ]}
                    secureTextEntry={secureTextEntry}
                    editable={editable}
                    onTouchStart={onTouchStart}
                    textContentType={textContentType}
                />
                {label && <Text style={[TextStyles.labelMedium, styles.label, styleLabel]}>{label}</Text>}
                {!!errorText && <Text style={[TextStyles.labelMedium, styles.errorText, styleError]}>{errorText}</Text>}
            </View>
        );
    }
Example #22
Source File: single-code-input.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
SingleCodeInput: React.FC<SingleCodeInputProps> = ({
  style,
  disabled = false,
  autoFocus = false,
  onChange,
  error,
  count,
  accessibilityHint,
  accessibilityLabel
}) => {
  const [value, setValue] = useState<string>('');
  const inputRef = createRef<TextInput>();
  const fontScale = PixelRatio.getFontScale();

  useEffect(() => {
    const isScreenReaderEnabled = (async function () {
      await AccessibilityInfo.isScreenReaderEnabled();
    })();
    if (autoFocus && !isScreenReaderEnabled) {
      inputRef.current?.focus();
    }
  }, [inputRef, autoFocus]);

  const onChangeTextHandler = (v: string) => {
    const validatedValue = v.replace(/[^a-zA-Z0-9]/g, '');
    setValue(validatedValue);

    if (!validatedValue) {
      return;
    }

    if (onChange) {
      onChange(validatedValue);
    }
  };

  const onFocusHandler = () => {
    if (error) {
      inputRef.current?.clear();
      inputRef.current?.focus();
      if (onChange) {
        onChange(value);
      }
    }
  };

  return (
    <View style={[styles.container, style]}>
      <TextInput
        ref={inputRef}
        selectTextOnFocus
        autoCapitalize="characters"
        style={[
          styles.input,
          {height: 60 * fontScale},
          error ? styles.errorBlock : styles.block
        ]}
        maxLength={count}
        keyboardType="default"
        returnKeyType="done"
        editable={!disabled}
        value={value}
        placeholder="——————"
        onFocus={onFocusHandler}
        onChangeText={onChangeTextHandler}
        accessibilityLabel={accessibilityLabel}
        accessibilityHint={accessibilityHint}
      />
    </View>
  );
}
Example #23
Source File: App.tsx    From Rapid-Application-Development-with-AWS-Amplify with MIT License 5 votes vote down vote up
App = () => {
  const [formState, setFormState] = useState(initialState);
  const [todos, setTodos] = useState<any[]>([]);

  useEffect(() => {
    fetchTodos();
  }, []);

  const setInput = (key: any, value: any):any => {
    setFormState({ ...formState, [key]: value });
  }

  const fetchTodos = async (): Promise<any> => {
    try {
      const todoData:any = await API.graphql(graphqlOperation(listTodos));
      const todos:any = todoData.data.listTodos.items;
      setTodos(todos);
    } catch (err) { 
      console.log('error fetching todos');
    }
  }

  const addTodo = async (): Promise<any> => {
    try {
      if (!formState.name || !formState.description) return;
      const todo = { ...formState };
      setTodos([...todos, todo] as SetStateAction<any[]>);
      setFormState(initialState);
      await API.graphql(graphqlOperation(createTodo, {input: todo}));
    } catch (err) {
      console.log('error creating todo:', err);
    }
  }

  return (
    <View style={styles.container}>
      <TextInput
        onChangeText={val => setInput('name', val)}
        style={styles.input}
        value={formState.name} 
        placeholder="Name"
      />
      <TextInput
        onChangeText={val => setInput('description', val)}
        style={styles.input}
        value={formState.description}
        placeholder="Description"
      />
      <Button title="Create Todo" onPress={addTodo} />
      {
        todos.map((todo, index) => (
          <View key={todo.id ? todo.id : index} style={styles.todo}>
            <Text style={styles.todoName}>{todo.name}</Text>
            <Text>{todo.description}</Text>
          </View>
        ))
      }
    </View>
  )
}
Example #24
Source File: items.tsx    From THUInfo with MIT License 5 votes vote down vote up
SettingsEditValue = <T extends string | number>({
	text,
	value,
	onValueChange,
}: {
	text: string;
	value: T;
	onValueChange: (newValue: T) => void;
}) => {
	const themeName = useColorScheme();
	const {colors} = themes(themeName);
	return (
		<View
			style={{
				padding: 8,
				paddingRight: 16,
				flexDirection: "row",
				justifyContent: "space-between",
				alignItems: "center",
			}}>
			<Text style={{fontSize: 17, flex: 4, color: colors.text}}>{text}</Text>
			<TextInput
				style={{
					fontSize: 15,
					flex: 1,
					backgroundColor: colors.themeBackground,
					color: colors.text,
					textAlign: "left",
					borderColor: "lightgrey",
					borderWidth: 1,
					borderRadius: 5,
					padding: 6,
				}}
				value={String(value)}
				onChangeText={(newText) => {
					if (typeof value === "string") {
						// @ts-ignore
						onValueChange(newText);
					} else if (!isNaN(Number(newText))) {
						// @ts-ignore
						onValueChange(Number(newText));
					}
				}}
				keyboardType={typeof value === "string" ? "default" : "numeric"}
			/>
		</View>
	);
}
Example #25
Source File: TextField.tsx    From swiftui-react-native with MIT License 5 votes vote down vote up
TextField: React.FC<TextFieldProps> = ({
  placeholder,
  text,
  onChange,
  fontSize,
  font = 'body',
  customFont,
  foregroundColor,
  fontWeight = 'regular',
  cornerRadius,
  backgroundColor,
  rotationEffect,
  scaleEffect,
  padding,
  border,
  frame,
  shadow,
  opacity,
  zIndex,
  style,
  alert,
  onAppear,
  onDisappear,
}) => {
  useAlert(alert);
  useLifecycle(onAppear, onDisappear);
  const colorScheme = useColorScheme();

  return (
    <TextInput
      style={[
        {
          opacity,
          zIndex,
          backgroundColor: getColor(backgroundColor, colorScheme),
          color: getColor(foregroundColor, colorScheme, 'label'),
          ...getCornerRadius(cornerRadius),
          ...getFont(font, fontSize, fontWeight, customFont),
          ...getPadding(padding),
          ...getFrame(frame),
          ...getBorder(border),
          ...getShadow(shadow),
          ...getTransform(scaleEffect, rotationEffect),
        },
        style,
      ]}
      placeholder={placeholder}
      placeholderTextColor={getColor('secondaryLabel', colorScheme)}
      value={text.value}
      onChangeText={(newText) => {
        text.setValue(newText);
        if (onChange) {
          onChange();
        }
      }}
    />
  );
}
Example #26
Source File: AnimatedText.tsx    From react-native-wagmi-charts with MIT License 5 votes vote down vote up
AnimatedTextInput = Animated.createAnimatedComponent(TextInput)
Example #27
Source File: NumberInput.tsx    From react-native-jigsaw with MIT License 5 votes vote down vote up
NumberInput: FC<Props> = ({
  onChangeText,
  value,
  defaultValue,
  ...props
}) => {
  const [currentStringNumberValue, setCurrentStringNumberValue] = useState("0");

  const formatValueToStringNumber = (valueToFormat?: number | string) => {
    if (valueToFormat != null) {
      if (isString(valueToFormat) && valueToFormat !== "") {
        if (/^0[1-9]$/.test(valueToFormat)) {
          return valueToFormat.slice(1);
        } else if (/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/.test(valueToFormat)) {
          return valueToFormat;
        } else {
          return currentStringNumberValue;
        }
      } else if (isNumber(valueToFormat) && !isNaN(valueToFormat)) {
        return valueToFormat.toString();
      }
    }

    return "0";
  };

  // set currentStringNumberValue as defaultValue prop if there is a differnce on first render only
  useEffect(() => {
    const defaultStringNumberValue = formatValueToStringNumber(defaultValue);

    if (currentStringNumberValue !== defaultStringNumberValue) {
      setCurrentStringNumberValue(defaultStringNumberValue);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleChangeText = (newValue: string) => {
    const newStringNumberValue = formatValueToStringNumber(newValue);
    const number = parseFloat(newStringNumberValue);

    setCurrentStringNumberValue(newStringNumberValue);
    onChangeText?.(number);
  };

  // run handleChangeText with value prop only when value prop changes (and first render to reset currentStringNumberValue)
  useEffect(() => {
    const nextStringNumberValue = formatValueToStringNumber(value);

    if (currentStringNumberValue !== nextStringNumberValue) {
      handleChangeText(nextStringNumberValue);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value]);

  return (
    <TextInput
      keyboardType="numeric"
      value={currentStringNumberValue}
      onChangeText={handleChangeText}
      {...props}
    />
  );
}
Example #28
Source File: Input.tsx    From react-native-crypto-wallet-app with MIT License 5 votes vote down vote up
Input = forwardRef<TextInput, InputProps>(({ ...rest }, ref) => {
  const props = useRestyle(restyleFunctions, rest);

  return <TextInput {...{ ref }} {...props} />;
})
Example #29
Source File: Input.tsx    From online-groceries-app with MIT License 5 votes vote down vote up
Input = ({label}: InputProps) => {
  return (
    <>
      <Text style={styles.inputLabel}>{label}</Text>
      <TextInput style={styles.input} />
    </>
  );
}