react-native#TextInput JavaScript 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: LoginScreen.js    From react-native-instagram-clone with MIT License 6 votes vote down vote up
export default function LoginScreen({_signInAsync}) {
  return (
    <View style={Styles.container}>
      <View style={Styles.logoContainer}>
        <Image
          source={images.logoBlack}
          style={{height: 70, resizeMode: 'contain'}}
        />
      </View>
      <View style={Styles.userNameContainer}>
        <TextInput
          style={Styles.userNameInput}
          placeholder="Telefon numarası, kullanıcı adı veya e-posta"
        />
      </View>
      <View style={Styles.passwordContainer}>
        <TextInput style={Styles.passwordInput} placeholder="Şifre" />
      </View>
      <View style={Styles.forgotPasswordContainer}>
        <TouchableOpacity>
          <Text style={Styles.forgotPasswordText}>Şifreni mi unuttun?</Text>
        </TouchableOpacity>
      </View>
      <TouchableOpacity
        style={Styles.loginContainer}
        onPress={() => _signInAsync}>
        <Text style={Styles.loginText}>Giriş Yap</Text>
      </TouchableOpacity>
    </View>
  );
}
Example #2
Source File: MessageComponent.js    From react-native-todolist with MIT License 6 votes vote down vote up
renderInputToolbar(props) {
    //Add the extra styles via containerStyle
    return <InputToolbar
      {...props}
      containerStyle={{
        borderTopWidth: 1.5,
        borderTopColor: 'transparent',
        height: 60
      }}>
      <TextInput
        multiline
        onContentSizeChange={e => this.setState({ chatHeight: e.nativeEvent.contentSize.height })}
      />
    </InputToolbar>
  }
Example #3
Source File: PlaceholderStyleTextInput.js    From haven with MIT License 6 votes vote down vote up
render() {
    const {
      placeholderStyle, style, onChange, inputRef, ...rest
    } = this.props;

    return (<TextInput
      ref={inputRef}
      {...rest}
      onChange={this.handleChange}
      style={this.state.placeholder ? [style, placeholderStyle] : style}
    />);
  }
Example #4
Source File: ForumItem.js    From RRWallet with MIT License 6 votes vote down vote up
render() {
    const { title, placeholder, renderInputRightView, secureTextEntry } = this.props;
    return (
      <View style={[styles.card, this.props.style]}>
        <View style={[styles.row, styles.border]}>
          <Text style={styles.title}>{title}</Text>
        </View>
        <View style={styles.inputWrap}>
          <TextInput
            underlineColorAndroid="transparent"
            numberOfLines={1}
            onChangeText={this._onChangeText}
            style={styles.input}
            placeholder={placeholder}
            placeholderTextColor={theme.textColor.placeHolder}
            returnKeyType="done"
            blurOnSubmit={true}
            secureTextEntry={secureTextEntry}
          />
          {renderInputRightView && renderInputRightView()}
        </View>
      </View>
    );
  }
Example #5
Source File: account.js    From actual with MIT License 6 votes vote down vote up
render() {
    const { accountName } = this.props;
    const { text } = this.state;

    return (
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          backgroundColor: colors.n11,
          marginVertical: 11,
          marginHorizontal: 11,
          borderRadius: 4,
          padding: 10
        }}
      >
        <Search width="20" height="20" style={{ color: colors.n7 }} />
        <TextInput
          value={text}
          onChangeText={this.onChange}
          placeholder={`Search ${accountName}`}
          placeholderTextColor={colors.n7}
          style={{ fontSize: 15, flex: 1, marginLeft: 4, padding: 0 }}
        />
      </View>
    );
  }
Example #6
Source File: input.js    From turkce-sozluk with MIT License 6 votes vote down vote up
Input = styled(TextInput).attrs(props => ({
  placeholderTextColor: theme.colors[props.placeholderTextColor] || '#999'
}))(
  compose(
    borderRadius,
    typography,
    space,
    color,
    size,
    shadow
  )
)
Example #7
Source File: Input.js    From ReactNavigationAuthenticationFlowsWithHooks with MIT License 6 votes vote down vote up
export function Input({style, ...props}) {
  return (
    <TextInput
      {...props}
      style={[styles.input, style]}
      placeholderTextColor={'darkgray'}
    />
  );
}
Example #8
Source File: index.js    From cometchat-pro-react-native-ui-kit with MIT License 6 votes vote down vote up
CometChatCreatePollOptions = (props) => {
  return (
    <View style={styles.ModalBodyItemContainer}>
      <View style={styles.ModalBodyItem}>
        <Text style={styles.SpecificItemText} />
      </View>
      <View style={styles.WrapperForInputAndDelete}>
        <TextInput
          style={styles.Inputbox}
          value={props.option.value}
          placeholder="Enter your option"
          onChangeText={(feedback) => {
            props.optionChangeHandler(feedback, props.option);
          }}
        />
        <TouchableOpacity
          style={styles.ContainerForDelete}
          onPress={() => {
            props.removePollOption(props.option);
          }}>
          <Image
            source={require('./resources/remove.png')}
            style={styles.RemoveImage}
          />
        </TouchableOpacity>
      </View>
    </View>
  );
}
Example #9
Source File: App.js    From celo-dappkit with MIT License 6 votes vote down vote up
render(){
    return (
      <View style={styles.container}>
        <Image resizeMode='contain' source={require("./assets/white-wallet-rings.png")}></Image>
        <Text>Open up client/App.js to start working on your app!</Text>
        
        <Text style={styles.title}>Login first</Text>
        <Button title="login()" 
          onPress={()=> this.login()} />
                <Text style={styles.title}>Account Info:</Text>
        <Text>Current Account Address:</Text>
        <Text>{this.state.address}</Text>
        <Text>Phone number: {this.state.phoneNumber}</Text>
        <Text>cUSD Balance: {this.state.cUSDBalance}</Text>

        <Text style={styles.title}>Read HelloWorld</Text>
        <Button title="Read Contract Name" 
          onPress={()=> this.read()} />
        <Text>Contract Name: {this.state.contractName}</Text>
        
        <Text style={styles.title}>Write to HelloWorld</Text>
        <Text>New contract name:</Text>
        <TextInput
          style={{  borderColor: 'black', borderWidth: 1, backgroundColor: 'white' }}
          placeholder="input new name here"
          onChangeText={text => this.onChangeText(text)}
          value={this.state.textInput}
          />
        <Button style={{padding: 30}} title="update contract name" 
          onPress={()=> this.write()} />
      </View>
    );
  }
Example #10
Source File: Input.js    From UltimateApp with MIT License 6 votes vote down vote up
Input = ({ fieldName, label, required, multiline, ...props }) => {
  const [isFocused, setIsFocused] = useState(false);
  const [field, meta] = useField(fieldName);

  const borderColor = isFocused ? styles.focusedInput : meta.error && meta.touched ? styles.errorInput : undefined;
  const multilineProps = multiline ? { multiline: true, numberOfLines: 3, textAlignVertical: 'top' } : undefined;

  return (
    <View style={styles.group}>
      <View style={styles.label}>
        {required && <Text style={styles.error}>* </Text>}
        <Text>{label}</Text>
      </View>
      <View style={[styles.input, borderColor]}>
        {meta.error && meta.touched && <Text style={styles.error}>{meta.error}</Text>}
        <TextInput
          testID={`input-${fieldName}`}
          onChangeText={field.onChange(fieldName)}
          value={field.value?.toString()}
          onFocus={() => setIsFocused(true)}
          onBlur={() => setIsFocused(false)}
          {...multilineProps}
          {...props}
        />
      </View>
    </View>
  );
}
Example #11
Source File: SearchBar.js    From covid-19-app with MIT License 6 votes vote down vote up
SearchBar = props => {
    return (
        <View style={{ flexDirection: 'row' }}>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Image
                    style={styles.searchBar.icon.image}
                    source={require('../assets/logo.png')}
                />
            </View>

            <View style={styles.searchBar.container}>
                <TextInput
                    style={styles.searchBar.inputStyle}
                    placeholder={props.label}
                    placeholderTextColor={styles.searchBar.placeholderColor}
                    onChangeText={props.onSearch}
                />
                <Image source={require('../assets/search.png')} style={styles.searchBar.logo} />
            </View>

            <TouchableOpacity style={{ paddingHorizontal: 3, justifyContent: 'center' }} onPress={props.changeLang}>
                <Image source={require('../assets/globe.png')} style={styles.searchBar.langImage} />
            </TouchableOpacity>
        </View>
    )
}
Example #12
Source File: BookSearch.js    From duofolio with GNU General Public License v3.0 6 votes vote down vote up
function BookSearch(props) {
	const [input, setInput] = useState('');

	function renderResults() {
		return input && props.searchResults
			? props.searchResults.map((result, i) => (
					<SearchItem {...result} onPress={props.goToLocation} key={i} />
			  ))
			: null;
	}

	return (
		<ScrollView style={styles.scrollView} contentContainerStyle={styles.scrollViewContent}>
			<TextInput
				value={input}
				onChangeText={setInput}
				placeholder="Search"
				allowFontScaling={false}
				returnKeyType="search"
				style={styles.input}
				onSubmitEditing={() => props.onSearch(input)}
			/>
			{renderResults()}
		</ScrollView>
	);
}
Example #13
Source File: CustomTextInput.js    From react-native-otp-login with MIT License 6 votes vote down vote up
CustomTextInput = function(props) {
  const {
    containerStyle,
    style,
    LeftComponent,
    RightComponent,
    refCallback,
    ...remainingProps
  } = props;

  return (
    <View style={[styles.containerStyle, containerStyle]}>
      {LeftComponent}
      <TextInput
        {...remainingProps}
        style={[styles.textInputStyle, GenericStyles.fill, style]}
        ref={refCallback}
      />
      {RightComponent}
    </View>
  );
}
Example #14
Source File: CCInput.js    From react-native-credit-card-input-plus with MIT License 6 votes vote down vote up
render() {
    const { label, value, placeholder, status, keyboardType,
            containerStyle, inputStyle, labelStyle,
            validColor, invalidColor, placeholderColor,
            additionalInputProps } = this.props;
    return (
      <TouchableOpacity onPress={this.focus}
        activeOpacity={0.99}>
        <View style={[containerStyle]}>
          { !!label && <Text style={[labelStyle]}>{label}</Text>}
          <TextInput ref="input"
            {...additionalInputProps}
            keyboardType={keyboardType}
            autoCapitalise="words"
            autoCorrect={false}
            style={[
              s.baseInputStyle,
              inputStyle,
              ((validColor && status === "valid") ? { color: validColor } :
              (invalidColor && status === "invalid") ? { color: invalidColor } :
              {}),
            ]}
            underlineColorAndroid={"transparent"}
            placeholderTextColor={placeholderColor}
            placeholder={placeholder}
            value={value}
            onFocus={this._onFocus}
            onChangeText={this._onChange} />
        </View>
      </TouchableOpacity>
    );
  }
Example #15
Source File: custom-input.js    From astrale with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param props
 * @returns {*}
 * @constructor
 */
function CustomInput(props) {
  const { colors } = useTheme();
  const maxLength = props.keyboardType === 'number-pad' ? 5 : null;
  return (
    <PaperTextInput
      {...props}
      style={[styles.input, { backgroundColor: colors.text + '00' }]}
      render={(props) => (
        <TextInput
          {...props}
          style={[styles.inputCustom, props.customStyle]}
          maxLength={maxLength}
        />
      )}
    />
  );
}
Example #16
Source File: Login.js    From ultimate-hackathon-starting-guide with MIT License 6 votes vote down vote up
export default function Login({navigation}) {
    const { signIn } = useContext(AuthContext);
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    return (
        <>
            <StatusBar barStyle='dark-content' />
            <SafeAreaView style={{flex : 1, backgroundColor: "#00FF00"}}>
                <Text style={{textAlign: "center"}}>Login</Text>
                <Text style={{textAlign: "left"}}>Email</Text>
                <TextInput style={{borderWidth: 2}} onChangeText={text => setEmail(text)} value={email} />
                <Text style={{textAlign: "left"}}>Password</Text>
                <TextInput style={{borderWidth: 2}} onChangeText={text => setPassword(text)} secureTextEntry={true} value={password} />
                <Button title="Submit" onPress={() => signIn({email, password})} />
                <Button title="Register" onPress={() => navigation.navigate('Register')} />
            </SafeAreaView>
        </>
    );
}
Example #17
Source File: TextDemo.js    From real-frontend with GNU General Public License v3.0 6 votes vote down vote up
TextDemo = ({
  theme,
  field: {
    value,
    name,
  },
  form,
  placeholder,
  multiline = false,
  keyboardType = 'default',
  onSubmitEditing,
  disabled,
}) => {
  const styling = styles(theme)
  const { t } = useTranslation()

  return (
    <View style={styling.root}>
      <TextInput
        style={styling.input}
        name={name}
        onChangeText={form.handleChange(name)}
        onBlur={form.handleBlur(name)}
        value={value}
        placeholder={placeholder}
        placeholderTextColor={theme.colors.placeholder}
        autoCapitalize="none"
        multiline={multiline}
        keyboardType={keyboardType}
        onSubmitEditing={onSubmitEditing}
        mode="outlined"
        dense={true}
        label={placeholder}
        disabled={disabled}
      />
      <ErrorMessage name={name} render={msg => <Text style={styling.error}>{msg}</Text>} />
    </View>
  )
}
Example #18
Source File: BLEReadCharacteristic.js    From BLEServiceDiscovery with GNU General Public License v3.0 6 votes vote down vote up
function BLEReadcharacteristic(ReduxStore) {

  const [text,setText] = useState({'text':'write something to device'});

    return(
        <SafeAreaView style={styles.container}>
          <Text>{ReduxStore.selectedCharacteristic.uuid}</Text>
            <FlatList
                data={[ReduxStore.selectedCharacteristic]}
                renderItem={({ item }) => 
                <>
                <Item characteristic={item} />
                <TextInput
                 onChangeText={(text) => setText({text})}
                  style={{ height: 40, color: 'black', borderColor: 'gray', borderWidth: 1 }}
                  value={text.text}
                />
                <Button
                  title="Write"
                  onPress={() => handleClick(ReduxStore,text.text)}
                ></Button>
                </>
                }
                keyExtractor={item => item.id.toString()}
                ListEmptyComponent={DataActivityIndicator}
            />
        </SafeAreaView>
    );
}
Example #19
Source File: Input.js    From id.co.moonlay-eworkplace-mobile with MIT License 6 votes vote down vote up
Input = ({ label, value, onChangeText, placeholder, secureTextEntry, multiline, numberOfLines }) => {
  const {inputStyle, labelStyle, containerStyle } = styles;

  return (
    <View style={containerStyle}>
      <Text style={labelStyle}>{label}</Text>
      <TextInput
        secureTextEntry={secureTextEntry}
        placeholder={placeholder}
        value={value}
        onChangeText={onChangeText}
        autoCorrect={false}
        multiline={multiline}
        numberOfLines={numberOfLines}
        style={inputStyle}
      />
    </View>
  );
}
Example #20
Source File: TextInput.js    From Done-With-It with MIT License 6 votes vote down vote up
function AppTextInput({ icon, width = "100%", ...otherProps }) {
	return (
		<View style={[styles.container, { width }]}>
			{icon && (
				<MaterialCommunityIcons
					name={icon}
					size={20}
					color={defaultStyles.colors.medium}
					style={styles.icon}
				/>
			)}
			<TextInput
				placeholderTextColor={defaultStyles.colors.medium}
				style={defaultStyles.text}
				{...otherProps}
			/>
		</View>
	);
}
Example #21
Source File: TextInput.js    From juken with MIT License 6 votes vote down vote up
TextInputComponent = ({ style, ...props } = {}) => {
  const colorScheme = useColorScheme();
  return <TextInput
    style={[
      styles.wrapper,
      colorScheme === "light" ? null : styles.wrapper_dark,
      ...(Array.isArray(style) ? style : [style])
    ]}
    {...props}
  />
}
Example #22
Source File: Start.js    From react-native-sdk with MIT License 6 votes vote down vote up
render() {
    return (
      <View style={styles.container}>
        <Text style={styles.label}>First Name</Text>
        <TextInput
          style={styles.input}
          onChangeText={(text) => this.onChangeText('firstName', text)}
          value={this.state.firstName}
        />
        <Text style={styles.label}>Last Name</Text>
        <TextInput
          style={styles.input}
          onChangeText={(text) => this.onChangeText('lastName', text)}
          value={this.state.lastName}
        />
        <Link
          style={styles.button}
          to={`/sdk/${this.state.firstName}/${this.state.lastName}`}>
          <Text style={styles.buttonText}>Start SDK</Text>
        </Link>
      </View>
    );
  }
Example #23
Source File: CreateComment.js    From reddit-clone with MIT License 6 votes vote down vote up
CreateComment = ({ onPress, setComment, comment, setIsFocused }) => {
  const { colors } = useTheme()
  const textInputRef = React.useRef()

  return (
    <View style={[styles.container, { backgroundColor: colors.bgColor }]}>
      <TextInput
        style={[
          styles.textInput,
          { backgroundColor: colors.background, borderColor: colors.border, color: colors.text }
        ]}
        ref={textInputRef}
        placeholder="Add a comment"
        placeholderTextColor={colors.text}
        onFocus={() => setIsFocused(true)}
        onBlur={() => setIsFocused(false)}
        onChangeText={setComment}
        maxLength={2000}
        autoCorrect={false}
        value={comment}
      />
      <TouchableOpacity
        onPress={() => {
          textInputRef.current.blur()
          onPress()
        }}
      >
        <Send color={colors.text} />
      </TouchableOpacity>
    </View>
  )
}
Example #24
Source File: CustomTextInput.jsx    From ovuli with MIT License 6 votes vote down vote up
CustomTextInput = ({ placeholder, type, onChangeText, name, style }) => {
  return (
    <TextInput
      placeholder={placeholder}
      name={name}
      onChangeText={onChangeText}
      type={type}
      style={[styles, style]}
    />
  );
}
Example #25
Source File: Input.js    From react-native-select-dropdown with MIT License 5 votes vote down vote up
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 #26
Source File: Form.js    From bluezone-app with GNU General Public License v3.0 5 votes vote down vote up
render() {
    const {intl, statusInfo, notifyObj} = this.props;
    const {formatMessage} = intl;
    const {phone, name, address, getDataSuccess, showCheckbox} = this.state;
    const statusButton = statusInfo || notifyObj.data.declare ? 'edit' : 'send';
    const infoValid = phone.length > 0 && name.length > 0 && address.length > 0;
    const disabledButton =
      !infoValid || statusInfo === 'success' || statusInfo === 'waiting';
    const buttonText =
      statusInfo === 'waiting'
        ? formatMessage(message.sending)
        : statusButton === 'send'
        ? formatMessage(message.send)
        : formatMessage(message.editInfo);
    return (
      <View style={[styles.containerForm]}>
        <Text style={styles.title}>
          {formatMessage(message.dangerTutorial)}
        </Text>
        <View style={{paddingTop: 10, paddingBottom: 5}}>
          <TextInput
            style={styles.inputFirst}
            onChangeText={this.onChangePhone}
            placeholder={formatMessage(message.phoneNumber)}
            placeholderTextColor={'#b5b5b5'}
            allowFontScaling={false}
            textContentType={'telephoneNumber'}
            keyboardType={'numeric'}
            value={phone}
          />
          <TextInput
            style={styles.input}
            onChangeText={this.onChangeName}
            placeholder={formatMessage(message.fullName)}
            placeholderTextColor={'#b5b5b5'}
            allowFontScaling={false}
            value={name}
          />
          <TextInput
            style={styles.input}
            onChangeText={this.onChangeAddress}
            placeholder={formatMessage(message.address)}
            placeholderTextColor={'#b5b5b5'}
            allowFontScaling={false}
            value={address}
          />
        </View>
        {showCheckbox && (
          <View
            style={{flexDirection: 'row', marginTop: 5, alignItems: 'center'}}>
            <CheckBox
              value={this.state.checkbox}
              onValueChange={this.onChangeCheckBox}
              style={{marginLeft: -7}}
            />
            <Text onPress={this.onChangeValueCheckBox} style={styles.checkbox}>
              Gửi kèm lịch sử tiếp xúc
            </Text>
          </View>
        )}
        <ButtonIconText
          onPress={this.onSend}
          disabled={disabledButton}
          text={buttonText}
          styleBtn={[
            styles.buttonSendSquare,
            {
              backgroundColor: disabledButton ? '#CCCCCC' : '#119a01',
            },
          ]}
          styleText={styles.textButton}
        />
        <View />
      </View>
    );
  }
Example #27
Source File: LoginForm.js    From Spring2020_MyFood_FrontEnd with GNU General Public License v3.0 5 votes vote down vote up
LoginForm = props  => {
      
    onPressLoginButton = () => {
        props.navigation.navigate("Home");
    };

    const [isModalVisible, setIsModalVisible] = useState(false);

    toggleModal = () => {
      setIsModalVisible(!isModalVisible)
     // this.setState({ isModalVisible: !this.state.isModalVisible });
    };

  return (
    <View style={styles.container}>
     <TextInput 
     placeholder= "Username"
     placeholderTextColor="#000"
     returnKeyType="next"
     autoCapitalize='none'
     autoCorrect={false}
     style={styles.input}
     />
     <TextInput 
     placeholder= "Password "
     placeholderTextColor="#000"
     secureTextEntry
     returnKeyType="go"
     style={styles.input}
     />

    <View style= {styles.button}>
        <TouchableOpacity style={styles.buttonContainer} onPress={this.onPressLoginButton}>
        <Text style={styles.buttonText}>LOGIN</Text>
    </TouchableOpacity>
    <TouchableOpacity style={{paddingTop: 20}}>
        <Text style={styles.otherButtonText}>Forget Password</Text>
    </TouchableOpacity>
    <TouchableOpacity style={{paddingTop: 10}}>
        <Text style={styles.otherButtonText} onPress={toggleModal} >SIGNUP</Text>
    </TouchableOpacity>
    <Modal isVisible={isModalVisible}>
          <View style={{ flex: 1 }}>
          <Button style={styles.cancelBtn} title="X" onPress={toggleModal} />
      {/* <FontAwesome style={{fontSize: 32}} icon={BrandIcons.github}/> */}

            <Register />
          </View>
        </Modal>
    </View>
    
    </View >
  );
}
Example #28
Source File: resources-search.js    From Solution-Starter-Kit-Cooperation-2020 with Apache License 2.0 5 votes vote down vote up
SearchResources = function ({ route, navigation }) {
  const [query, setQuery] = React.useState({ type: 'Food', name: '' });
  const [items, setItems] = React.useState([]);
  const [info, setInfo] = React.useState('');

  const Item = (props) => {
    return (
      <TouchableOpacity style={styles.itemTouchable}
          onPress={() => { navigation.navigate('Map', { item: props }); }}>
        <View style={styles.itemView}>
          <Text style={styles.itemName}>{props.name}</Text>
          <Text style={styles.itemQuantity}> ( {props.quantity} ) </Text>
        </View>
        <Text style={styles.itemDescription}>{props.description}</Text>
      </TouchableOpacity>
    );
  };

  const searchItem = () => {
    const payload = {
      ...query
    };

    search(payload)
      .then((results) => {
        setInfo(`${results.length} result(s)`)
        setItems(results);
      })
      .catch(err => {
        console.log(err);
        Alert.alert('ERROR', 'Please try again. If the problem persists contact an administrator.', [{text: 'OK'}]);
      });
  };

  return (
    <View style={styles.outerView}>
      <View style={styles.inputsView}>
        <Text style={styles.label}>Type</Text>
        <PickerSelect
          style={{ inputIOS: styles.selector }}
          value={query.type}
          onValueChange={(t) => setQuery({ ...query, type: t })}
          items={[
              { label: 'Food', value: 'Food' },
              { label: 'Help', value: 'Help' },
              { label: 'Other', value: 'Other' }
          ]}
        />
        <Text style={styles.label}>Name</Text>
        <TextInput
          style={styles.textInput}
          value={query.name}
          onChangeText={(t) => setQuery({ ...query, name: t})}
          onSubmitEditing={searchItem}
          returnKeyType='send'
          enablesReturnKeyAutomatically={true}
          placeholder='e.g., Tomotatoes'
          blurOnSubmit={false}
        />
        <TouchableOpacity onPress={searchItem}>
          <Text style={styles.button}>Search</Text>
        </TouchableOpacity>
      </View>

      <Text style={styles.searchResultText}>{info}</Text>

      <FlatList style={styles.flatListView}
        data={items}
        renderItem={({ item }) => <Item {...item} />}
        keyExtractor={item => item.id || item['_id']}
      />
    </View>
  );
}
Example #29
Source File: Search.js    From Legacy with Mozilla Public License 2.0 5 votes vote down vote up
export default function SearchScreen({ navigation }) {
  var { t } = useTranslation();
  var theme = useSelector(i => i.themes[i.theme])
  var input = React.useRef();
  var [value, setValue] = React.useState('');
  var [search, setSearch] = React.useState('');
  var [timeoutC, setTimeoutC] = React.useState(null);
  function onValue(val) {
    if (timeoutC) clearTimeout(timeoutC)
    setValue(val);
    setTimeoutC(setTimeout(() => {
      return setSearch(val);
    }, 500))
  }
  var dispatch = useDispatch();

  var reqData = {
    endpoint: 'user/find',
    data: { text: search },
    cuppazee: true
  }
  var users = useSelector(i => i.request_data[stringify(reqData)] ?? {})
  useFocusEffect(
    React.useCallback(() => {
      if (search.length >= 1) dispatch(request.add(reqData))
      return () => {
        if (search.length >= 1) dispatch(request.remove(reqData))
      };
    }, [search])
  );
  return (
    <ScrollView
      contentContainerStyle={{ width: 600, maxWidth: "100%", alignItems: "stretch", flexDirection: "column", alignSelf: "center", padding: 4 }}
      style={{ flex: 1, backgroundColor: theme.page.bg }}>
      <View style={{ padding: 4, width: "100%" }}>
        <Card noPad cardStyle={{ flexDirection: "row", backgroundColor: "#fff", alignItems: "stretch" }}>
          <TextInput
            onSubmitEditing={() => setSearch(value)}
            ref={input}
            style={{ paddingHorizontal: 8, flex: 1, borderRadius: 8, borderBottomLeftRadius: 8, height: 40 }}
            onChangeText={onValue}
            value={value}
            returnKeyType="search"
          />
        </Card>
      </View>
      <View style={{ padding: 4 }}>
        <Card noPad>
          <View>
            {search.length < 3 && <Text allowFontScaling={false} style={{ textAlign: "center", ...font("bold"), fontSize: 16, color: theme.page_content.fg, marginVertical: 4 }}>Type in your Username</Text>}
            {search.length >= 3 && !users?.data?.users && <View style={{ height: 100, justifyContent: "center", alignItems: "center" }}>
              <ActivityIndicator size={32} color={theme.page_content.fg} />
            </View>}
            {users?.data?.users?.length === 0 && <Text allowFontScaling={false} style={{ textAlign: "center", ...font("bold"), fontSize: 16, color: theme.page_content.fg }}>{t('search:empty')}</Text>}
            {users?.data?.users?.slice?.(0, 20)?.map?.(i => <TouchableRipple onPress={() => navigation.navigate('CompetitionAuth', { username: i.username })}>
              <View key={i.clan_id} style={{ padding: 4, flexDirection: "row", alignItems: "center" }}>
                <Image style={{ height: 24, width: 24, marginRight: 8, marginLeft: 4, borderRadius: 12 }} source={{ uri: i.avatar ?? `https://munzee.global.ssl.fastly.net/images/avatars/ua${Number(i.user_id).toString(36)}.png` }} />
                <View style={{ flex: 1 }}>
                  <Text allowFontScaling={false} style={{ ...font("bold"), fontSize: 16, color: theme.page_content.fg }}>{i.username}</Text>
                  <Text allowFontScaling={false} style={{ ...font("bold"), fontSize: 12, color: theme.page_content.fg }}>#{i.user_id}</Text>
                </View>
                <MaterialCommunityIcons size={24} name="chevron-right" color={theme.page_content.fg} />
              </View>
            </TouchableRipple>)}
          </View>
        </Card>
      </View>
    </ScrollView>
  );
}