native-base#Button JavaScript Examples
The following examples show how to use
native-base#Button.
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: Error.js From react-native-expo-starter-kit with MIT License | 6 votes |
Error = ({ title, content, tryAgain }) => (
<Container style={{ flex: 1 }}>
<View style={{ alignSelf: 'center' }}>
<Spacer size={20} />
<H3 style={{ textAlign: 'center' }}>{title}</H3>
<Text style={{ textAlign: 'center', marginBottom: 20 }}>{content}</Text>
{tryAgain && (
<Button block onPress={tryAgain}>
<Text>Try Again</Text>
</Button>
)}
<Spacer size={20} />
</View>
</Container>
)
Example #2
Source File: ReportIntroScreen.js From pandoa with GNU General Public License v3.0 | 6 votes |
//import VirusImage from "../assets/images/infoSimple";
export default function ReportIntroScreen({ navigation }) {
return (
<View
style={styles.container}
contentContainerStyle={styles.contentContainer}
>
<View style={styles.introWrapper}>
<VirusImage width={220} style={styles.image} />
<Text style={styles.title}>No case reported</Text>
<Text style={styles.subTitle}>
None of your positions will be send to the internet until you report a
case.
</Text>
<Button primary onPress={() => navigation.push("ReportDetail")}>
<Text>Report infection</Text>
</Button>
</View>
</View>
);
}
Example #3
Source File: WarningDetailScreen.js From pandoa with GNU General Public License v3.0 | 6 votes |
//import VirusImage from "../assets/images/infoSimple";
export default function WarningDetailScreen({ navigation }) {
return (
<View
style={styles.container}
contentContainerStyle={styles.contentContainer}
>
<View style={styles.introWrapper}>
<VirusImage width={220} style={styles.image} />
<Text style={styles.title}>No case reported</Text>
<Text style={styles.subTitle}>
None of your positions will be send to the internet until you report a
case.
</Text>
<Button primary onPress={() => navigation.push("ReportDetail")}>
<Text>Report infection</Text>
</Button>
</View>
</View>
);
}
Example #4
Source File: index.js From aws-appsync-refarch-offline with MIT No Attribution | 5 votes |
function Catalog(props) {
const [loading, setLoading] = useState(false);
const [products, setProducts] = useState([]);
const order = useSelector(state => state.order);
const dispatch = useDispatch();
useEffect(() => {
fetchProducts();
}, []);
async function fetchProducts() {
const data = await DataStore.query(Product);
setProducts(data);
};
function checkoutBtnHandler() {
return props.navigation.push('Checkout');
}
function addProductHandler(product) {
dispatch(addLineItem(product));
}
const productList = products.map(product => (
<ListItem thumbnail key={product.id}>
<Left>
<Thumbnail square source={{ uri: product.image }} />
</Left>
<Body>
<Text>{product.name}</Text>
<Text note numberOfLines={1}>${product.price}</Text>
</Body>
<Right>
<Button onPress={() => addProductHandler(product)}>
<Text>Add</Text>
</Button>
</Right>
</ListItem>
));
return (
<Container>
<Content refreshControl={
<RefreshControl
onRefresh={fetchProducts}
refreshing={loading}
/>
}>
<Button block info style={styles.checkoutBtn} onPress={checkoutBtnHandler}>
<Text style={styles.quantityText}>{order.totalQty}</Text>
<Text style={styles.subtotalTxt}>Subtotal ${order.subtotal.toFixed(2)}</Text>
</Button>
<List>
{productList}
</List>
</Content>
</Container>
);
}
Example #5
Source File: index.js From aws-appsync-refarch-offline with MIT No Attribution | 5 votes |
Settings = (props) => {
async function createProducts() {
try {
await loadProducts();
Toast.show({
text: 'Products loaded, pull to refresh',
buttonText: "Ok",
duration: 3000
});
props.navigation.navigate('Checkout');
} catch(error) {
Toast.show({
text: error,
buttonText: "Ok",
duration: 3000
});
}
}
async function clearDataStore() {
await DataStore.clear();
Toast.show({
text: 'Storage cleared, pull to refresh',
buttonText: "Ok",
duration: 3000
});
props.navigation.navigate('Checkout');
}
return (
<Container>
<Content>
<Button block info style={styles.settingsBtn} onPress={createProducts}>
<Text>Create dummy products</Text>
</Button>
<Button block info style={styles.settingsBtn} onPress={clearDataStore}>
<Text>Clear local storage</Text>
</Button>
</Content>
</Container>
);
}
Example #6
Source File: Transaction.js From web3-react-native with MIT License | 5 votes |
Transaction = ({ transaction, onRequestViewTransaction, ...extraProps }) => {
return (
<Card
>
<CardItem
header
bordered
>
<Text
children="Some Transaction Name"
/>
</CardItem>
<CardItem
bordered
>
<Icon active name="pricetag" />
<Text
style={styles.details}
children={transaction.transactionHash}
/>
</CardItem>
<CardItem
>
<Body
style={styles.buttons}
>
<View
style={styles.buttonContainer}
>
<Button
onPress={onRequestViewTransaction}
success
>
<Icon name="eye" />
<Text
children="View Transaction"
/>
</Button>
</View>
</Body>
</CardItem>
</Card>
);
}
Example #7
Source File: Wallet.js From web3-react-native with MIT License | 5 votes |
Wallet = ({ wallet, onRequestAddFunds, onRequestMakeTransaction, ...extraProps }) => {
return (
<Card
>
<CardItem
header
bordered
>
<Text
children="Some Wallet Name"
/>
</CardItem>
<CardItem
bordered
>
<Icon active name="wallet" />
<Text
style={styles.details}
children={wallet.address}
/>
</CardItem>
<CardItem
>
<Body
style={styles.buttons}
>
<View
style={styles.buttonContainer}
>
<Button
onPress={onRequestAddFunds}
success
>
<Icon name="water" />
<Text
children="Faucet"
/>
</Button>
</View>
<View
style={styles.buttonContainer}
>
<Button
onPress={onRequestMakeTransaction}
primary
>
<Icon name="cash" />
<Text
children="Send"
/>
</Button>
</View>
</Body>
</CardItem>
</Card>
);
}
Example #8
Source File: Form.js From react-native-expo-starter-kit with MIT License | 5 votes |
ArticlesForm = ({
error, loading, success, onFormSubmit, defaultValues,
}) => {
const {
register, handleSubmit, errors, setValue,
} = useForm({ defaultValues });
useEffect(() => {
register({ name: 'email' }, { required: errorMessages.missingEmail });
}, [register]);
return (
<Container>
<Content padder>
<Header
title="Example form"
content="When you submit the form, it'll simply save to your redux store"
/>
{error && <Messages message={error} />}
{loading && <Messages type="info" message="Loading..." />}
{success && <Messages type="success" message={success} />}
<Form>
<Item stackedLabel>
<Label>Email*</Label>
<Input
type="text"
autoCapitalize="none"
placeholder="[email protected]"
keyboardType="email-address"
defaultValue={defaultValues.email || ''}
onChangeText={(value) => setValue('email', value)}
/>
</Item>
{errors.email && <Text>{errors.email.message}</Text>}
<Spacer size={20} />
<Button block onPress={handleSubmit(onFormSubmit)} disabled={loading}>
<Text>{loading ? 'Loading' : 'Submit'}</Text>
</Button>
</Form>
</Content>
</Container>
);
}
Example #9
Source File: List.js From react-native-expo-starter-kit with MIT License | 5 votes |
ArticlesList = ({
error, loading, listFlat, reFetch, meta,
}) => {
if (error) {
return <Error content={error} tryAgain={reFetch} />;
}
if (listFlat.length < 1) {
return <Error content={errorMessages.articlesEmpty} />;
}
return (
<Container style={{ padding: 10 }}>
<FlatList
data={listFlat}
onRefresh={() => reFetch({ forceSync: true })}
refreshing={loading}
renderItem={({ item }) => (
<Card style={{ opacity: item.placeholder ? 0.3 : 1 }}>
<TouchableOpacity
activeOpacity={0.8}
onPress={() => (
!item.placeholder
? Actions.articlesSingle({ id: item.id, title: item.name })
: null
)}
style={{ flex: 1 }}
>
<CardItem cardBody>
{!!item.image && (
<Image
source={{ uri: item.image }}
style={{
height: 100,
width: null,
flex: 1,
overflow: 'hidden',
borderRadius: 5,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
}}
/>
)}
</CardItem>
<CardItem cardBody>
<Body style={{ paddingHorizontal: 15 }}>
<Spacer size={10} />
<Text style={{ fontWeight: '800' }}>{item.name}</Text>
<Spacer size={15} />
{!!item.excerpt && <Text>{item.excerpt}</Text>}
<Spacer size={5} />
</Body>
</CardItem>
</TouchableOpacity>
</Card>
)}
keyExtractor={(item) => `${item.id}-${item.name}`}
ListFooterComponent={(meta && meta.page && meta.lastPage && meta.page < meta.lastPage)
? () => (
<React.Fragment>
<Spacer size={20} />
<Button
block
bordered
onPress={() => reFetch({ incrementPage: true })}
>
<Text>Load More</Text>
</Button>
</React.Fragment>
) : null}
/>
<Spacer size={20} />
</Container>
);
}
Example #10
Source File: BottomSheetWarnings.js From pandoa with GNU General Public License v3.0 | 5 votes |
render() {
const { contentPosition, filteredWarnings, navigation } = this.props;
const renderInnerDetails = () => {
return (
<View style={styles.panelInner}>
<WarningList navigation={navigation} />
</View>
);
};
const renderInnerHeader = () => {
return (
<>
<View style={styles.headerShadow} />
<View style={styles.headerInner}>
<View style={styles.panelHeader}>
<View style={styles.panelHandle} />
</View>
<View style={styles.panelTitleWrapper}>
<Text style={styles.panelTitle}>
{filteredWarnings >= 1 ? filteredWarnings : "No"} Warnings
</Text>
<Button rounded small style={styles.buttonUpdate}>
<Ionicons
style={styles.buttonUpdateIcon}
name="md-refresh"
size={19}
color="#fff"
/>
<Text style={styles.buttonUpdateText}>Check overlap</Text>
</Button>
</View>
</View>
</>
);
};
return (
<BottomSheet
ref={this.bottomSheetRef}
contentPosition={contentPosition}
snapPoints={[65, 238, 600]}
renderContent={renderInnerDetails}
renderHeader={renderInnerHeader}
/>
);
}
Example #11
Source File: StatusView.js From WhatsApp-Clone with MIT License | 4 votes |
StatusView = ({navigation}) => {
var [state, dispatch] = useReducer(statusReducer, statusState);
var {statusData, recentStatusList, viewedStatusList, refresh} = state;
useFocusEffect(
React.useCallback(() => {
getUserStatusFromAPI(dispatch);
}, []),
);
useEffect(() => {
listenSocket();
// return () => {
// alert('STATUS DISCONNECTED');
// socket.removeListener(constants.USER_STATUS);
// };
}, []);
function listenSocket() {
// socket.removeListener(constants.CHAT_LIST);
socket.on(constants.USER_STATUS, async statusModel => {
const id = await getLocalData(constants.USER_ID);
if (statusModel.userId != id) {
console.log('STATUS RECEIVED');
getUserStatusFromAPI(dispatch);
}
});
}
return (
<Container>
<ScrollView nestedScrollEnabled style={{flex: 1, paddingBottom: 200}}>
<View>
<MyStatusView
navigation={navigation}
statusData={statusData}
isUser
isBorder={false}
/>
{recentStatusList.length > 0 && (
<View>
<_Divider style={{borderBottomWidth: 5}} />
<Text style={[DEFAULT_STYLES.poppinsSemiBold, styles.userTime]}>
RECENT UPDATES
</Text>
<RecentStatusView
navigation={navigation}
statusData={recentStatusList}
/>
</View>
)}
{viewedStatusList.length > 0 && (
<View>
<_Divider style={{borderBottomWidth: 5}} />
<Text style={[DEFAULT_STYLES.poppinsSemiBold, styles.userTime]}>
VIEWED UPDATES
</Text>
<ViewedStatusView
navigation={navigation}
statusData={viewedStatusList}
/>
</View>
)}
</View>
</ScrollView>
<View
style={{
flexDirection: 'column',
position: 'absolute',
bottom: 20,
right: 20,
}}>
<Button
rounded
style={{
backgroundColor: APP_BG_COLOR,
width: 50,
alignSelf: 'center',
height: 50,
}}>
<Icon
style={{color: TEXT_SUBTITLE, fontSize: 22}}
name="pencil"
type="MaterialCommunityIcons"
/>
</Button>
<Button
rounded
color={GREEN}
style={styles.btnView}
onPress={() => {
navigation.navigate(NAV_TYPES.CAMERA_VIEW, {});
}}>
<Thumbnail circular source={ADD_STATUS} style={styles.thumbView} />
</Button>
</View>
{/* <Fab
active={true}
direction="up"
style={{backgroundColor: '#5067FF', position: 'absolute'}}
position="bottomRight">
<Thumbnail source={ADD_STATUS} />
<Button style={{backgroundColor: '#EEF5F6'}}>
<Icon
style={{color: TEXT_SUBTITLE, fontSize: 24}}
name="pencil"
type="MaterialCommunityIcons"
/>
</Button>
</Fab> */}
</Container>
);
}
Example #12
Source File: RegisterScreen.js From WhatsApp-Clone with MIT License | 4 votes |
RegisterScreen = ({navigation}) => {
const [countryCode, setCountryCode] = useState('');
const [country, setCountry] = useState('');
const [userName, setUserName] = useState('');
const [mobile, setMobile] = useState('');
const [isLoading, setLoading] = useState(false);
useEffect(() => {
getLocalData(constants.USER_ID)
.then(userID => {
console.log('Login userID => ', userID);
if (userID && userID != null && userID != '') {
navigation.dispatch(StackActions.replace(NAV_TYPES.HOME_SCREEN));
}
})
.catch(err => {
console.log('Login Error => ', err);
});
}, []);
const onSelect = country => {
console.log(country);
setCountryCode(country.cca2);
setCountry(country);
};
const onSignUpClick = () => {
if (country === '') {
showToast({text: 'Select your Country', type: 'danger'});
} else if (userName === '') {
showToast({text: 'Enter your Name', type: 'danger'});
} else if (mobile === '') {
showToast({text: 'Enter your Mobile Number', type: 'danger'});
} else {
setLoading(!isLoading);
loginUser(getLoginModel(userName, mobile))
.then(res => {
setLoading(isLoading);
console.log('TOKEN : ', res.headers.token);
setUserName('');
setMobile('');
console.log('LOGIN RESPONSE => ' + JSON.stringify(res));
if (res.data.success) {
storeLocalData(constants.ACCESS_TOKEN, res.headers.token);
storeLocalData(constants.USER_ID, res.data.id);
storeLocalData(constants.USER_NAME, userName);
navigation.navigate(NAV_TYPES.HOME_SCREEN, {});
}
})
.catch(error => {
console.log('LOGIN ERROR ', error);
});
}
};
const onLoginClick = () => {
navigation && navigation.goBack();
};
return (
<SafeAreaView style={container}>
{isLoading && <LoadingComponent />}
{/* {!isLoading && ( */}
<Root style={[container, {flexDirection: 'column'}]}>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.keyboardView}>
<View style={styles.headerView}>
<Icon type="FontAwesome" name="whatsapp" style={styles.logoStyle} />
<_Text style={styles.logoTextStyle}>{constants.APP_NAME}</_Text>
</View>
<ScrollView
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
flex: 1,
justifyContent: 'center',
}}>
<View style={styles.contentView}>
<_Text description style={[poppinsRegular, styles.inputStyle]}>
Country
</_Text>
<View style={{flexDirection: 'column'}}>
{/* <_TextInput editable={true} style={{width:'20%'}} /> */}
<CountryPicker
containerButtonStyle={{
height: 40,
marginTop: 5,
justifyContent: 'center',
}}
countryCode={countryCode}
withCountryNameButton={true}
visible={false}
withFlag={true}
withCloseButton={true}
withAlphaFilter={true}
withCallingCode={true}
// withCurrency={true}
withEmoji={true}
withCountryNameButton={true}
// withCurrencyButton={true}
// withCallingCodeButton={true}
withFilter={true}
withModal={true}
onSelect={onSelect}
/>
<View style={{height: '3%', backgroundColor: GREEN}} />
</View>
<View style={{flexDirection: 'column', marginTop: '-4%'}}>
<_Text description style={[poppinsRegular, styles.labelStyle]}>
Enter Name
</_Text>
<_TextInput
value={userName}
inputStyle={[poppinsMedium, styles.inputStyle]}
floatingLabel={false}
keyboardType={'default'}
containerStyle={{width: '100%', marginLeft: 0}}
onChangeText={data => {
setUserName(data.value);
}}
/>
<_Text description style={[poppinsRegular, styles.labelStyle]}>
Mobile Number
</_Text>
<_TextInput
value={mobile}
inputStyle={[poppinsMedium, styles.inputStyle]}
floatingLabel={false}
keyboardType={'numeric'}
containerStyle={{width: '100%', marginLeft: 0}}
onChangeText={data => {
setMobile(data.value);
}}
/>
</View>
<View style={styles.buttonLoginView}>
<Button onPress={() => onSignUpClick()} style={styles.login}>
<Text style={{fontSize: 18, fontWeight: 'bold'}}>
Sign Up
</Text>
</Button>
<BorderlessButton
onPress={() => onLoginClick()}
style={styles.buttonSignupView}>
<Text style={styles.signup}>Login</Text>
</BorderlessButton>
</View>
</View>
</ScrollView>
</KeyboardAvoidingView>
</Root>
</SafeAreaView>
);
}
Example #13
Source File: OTPValidation.js From WhatsApp-Clone with MIT License | 4 votes |
OTPValidation = ({navigation}) => {
const [countryCode, setCountryCode] = useState('');
const [country, setCountry] = useState('');
const onSelect = country => {
console.log(country);
setCountryCode(country.cca2);
setCountry(country);
};
return (
// <SafeAreaView>
<View style={[container, {flexDirection: 'column'}]}>
<View
style={{
backgroundColor: GREEN,
height: '30%',
justifyContent: 'center',
alignItems: 'center',
}}>
<Icon
type="FontAwesome"
name="whatsapp"
style={{
fontSize: 50,
color: WHITE,
justifyContent: 'center',
alignSelf: 'center',
}}
/>
<_Text style={{marginTop: '2%', color: WHITE, fontSize: 26}}>
Whatsapp
</_Text>
</View>
<ScrollView
keyboardShouldPersistTaps="always"
style={{flexGrow: 1, height: '100%'}}
// contentContainerStyle={{
// // flex: 1,
// justifyContent: 'center',
// flexGrow:1
// }}
>
<View
style={{
margin: '6%',
flex: 1,
flexDirection: 'column',
height: '100%',
justifyContent: 'flex-start',
}}>
<_Text
title
style={[
poppinsMedium,
{marginTop: '10%', fontSize: 16, alignSelf: 'center'},
]}>
Waiting to automatically detect the sms sent to +91 8850987832
</_Text>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
marginTop: '10%',
marginBottom: '5%',
}}>
<_TextInput
editable={true}
maxLength={1}
textAlign={'center'}
containerStyle={styles.otpView1}
inputStyle={styles.otpLabelView}
/>
<_TextInput
editable={true}
maxLength={1}
textAlign={'center'}
containerStyle={styles.otpView}
inputStyle={styles.otpLabelView}
/>
<_TextInput
editable={true}
maxLength={1}
textAlign={'center'}
containerStyle={styles.otpView}
inputStyle={styles.otpLabelView}
/>
<_TextInput
editable={true}
maxLength={1}
textAlign={'center'}
containerStyle={styles.otpView}
inputStyle={styles.otpLabelView}
/>
</View>
<View style={{flexDirection: 'row'}}>
<_Text description style={(poppinsRegular, styles.resendOtpStyle)}>
Didn't receive the code ?
</_Text>
<_Text
description
style={[
poppinsRegular,
styles.resendOtpStyle,
{marginLeft: 10, color: GREEN, fontWeight: 'bold'},
]}>
RESEND CODE
</_Text>
</View>
</View>
</ScrollView>
<View
style={{
alignSelf: 'flex-end',
right: '3%',
bottom: '3%',
}}>
<Button
style={{
width: 60,
height: 60,
backgroundColor: GREEN,
}}
onPress={() => navigation.navigate(NAV_TYPES.HOME_SCREEN)}
rounded>
<Icon type="MaterialCommunityIcons" name="arrow-right" />
</Button>
</View>
</View>
// </SafeAreaView>
);
}
Example #14
Source File: LoginScreen.js From WhatsApp-Clone with MIT License | 4 votes |
LoginScreen = ({navigation}) => {
const [userName, setUserName] = useState('');
const [mobile, setMobile] = useState('');
const [isLoading, setLoading] = useState(false);
useEffect(() => {
getLocalData(constants.USER_ID)
.then(userID => {
console.log('Login userID => ', userID);
if (userID && userID != null && userID != '') {
navigation.dispatch(StackActions.replace(NAV_TYPES.HOME_SCREEN));
}
})
.catch(err => {
console.log('Login Error => ', err);
});
}, []);
const onLoginClick = () => {
if (userName === '') {
showToast({text: 'Enter your Name', type: 'danger'});
} else if (mobile === '') {
showToast({text: 'Enter your Mobile Number', type: 'danger'});
} else {
setLoading(!isLoading);
loginUser(getLoginModel(userName, mobile))
.then(res => {
console.log('LOGIN RESPONSE => ' + JSON.stringify(res));
if (res.data.success) {
setLoading(isLoading);
console.log('TOKEN : ', res.headers.token);
setUserName('');
setMobile('');
console.log('LOGIN RESPONSE => ' + JSON.stringify(res));
storeLocalData(constants.ACCESS_TOKEN, res.headers.token);
storeLocalData(constants.USER_ID, res.data.id);
storeLocalData(constants.USER_NAME, userName);
navigation.navigate(NAV_TYPES.HOME_SCREEN, {});
}
})
.catch(error => {
console.log('LOGIN ERROR ', error);
});
}
};
const onSignUpClick = () => {
navigation.navigate(NAV_TYPES.REGISTER, {});
};
return (
<SafeAreaView style={container}>
{isLoading && <LoadingComponent />}
{/* {!isLoading && ( */}
<Root style={[container, {flexDirection: 'column'}]}>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
style={styles.keyboardView}>
<View style={styles.headerView}>
<Icon type="FontAwesome" name="whatsapp" style={styles.logoStyle} />
<_Text style={styles.logoTextStyle}>{constants.APP_NAME}</_Text>
</View>
<ScrollView
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
flex: 1,
justifyContent: 'center',
}}>
<View style={styles.contentView}>
<View style={{flexDirection: 'column'}}>
<_Text description style={[poppinsRegular, styles.labelStyle]}>
Enter Name
</_Text>
<_TextInput
value={userName}
inputStyle={[poppinsMedium, styles.inputStyle]}
floatingLabel={false}
keyboardType={'default'}
containerStyle={{width: '100%', marginLeft: 0}}
onChangeText={data => {
setUserName(data.value);
}}
/>
<_Text description style={[poppinsRegular, styles.labelStyle]}>
Mobile Number
</_Text>
<_TextInput
value={mobile}
inputStyle={[poppinsMedium, styles.inputStyle]}
floatingLabel={false}
keyboardType={'numeric'}
containerStyle={{width: '100%', marginLeft: 0}}
onChangeText={data => {
setMobile(data.value);
}}
/>
</View>
<View style={styles.buttonLoginView}>
<Button onPress={() => onLoginClick()} style={styles.login}>
<Text style={{fontSize: 18, fontWeight: 'bold'}}>Login</Text>
</Button>
<BorderlessButton
onPress={() => onSignUpClick()}
style={styles.buttonSignupView}>
<Text style={styles.signup}>Sign Up</Text>
</BorderlessButton>
</View>
</View>
</ScrollView>
</KeyboardAvoidingView>
</Root>
{/* )} */}
</SafeAreaView>
);
}
Example #15
Source File: ChatTextInput.js From WhatsApp-Clone with MIT License | 4 votes |
ChatTextInput = ({params, onSendMessage, isStatus, onResetClick}) => {
const [message, setMessage] = useState('');
const [keyboardPadding, setKeyboardPadding] = useState(5);
useEffect(() => {
let listener1 = Keyboard.addListener('keyboardWillShow', onShowKeyboard);
let listener2 = Keyboard.addListener('keyboardWillHide', onHideKeyboard);
return () => {
listener1.remove();
listener2.remove();
};
}, []);
function onShowKeyboard(e) {
// alert('Keyboard Shown');
console.log(e);
setKeyboardPadding(
(e.endCoordinates.height - e.startCoordinates.height) / 2,
);
}
function onHideKeyboard(e) {
// alert('Keyboard Hidden');
setKeyboardPadding(0);
}
const getChatRoomInput = () => {
return (
<View style={{flexDirection: 'row'}}>
<Item rounded style={{backgroundColor: WHITE, flex: 1}}>
<Icon
name="smiley"
type="Octicons"
style={[styles.menuIcons, {marginLeft: 5}]}
/>
<Input
multiline
style={styles.userMessage}
placeholder="Type a message ..."
placeholderTextColor={LIGHT_GRAY}
value={message}
onChangeText={text => {
setMessage(text);
}}
/>
<Icon name="attachment" type="Entypo" style={styles.menuIcons} />
<Icon
name="camera"
type="MaterialCommunityIcons"
style={[styles.menuIcons, {marginRight: 5}]}
/>
</Item>
<Button
icon
rounded
large
style={styles.sendIconView}
onPress={() => {
onSendMessage(message);
setMessage('');
}}>
<Icon
name={message === '' ? 'microphone' : 'send'}
type="MaterialCommunityIcons"
style={styles.sendIcon}
/>
</Button>
</View>
);
};
const getStatusInput = () => {
return (
<View
style={{
flexDirection: 'row',
paddingBottom: '2%',
justifyContent: 'center',
}}>
<Button
rounded
style={styles.sendStatusIconView}
onPress={() => {
onResetClick();
setMessage('');
}}>
<Icon
name="camera"
type="MaterialCommunityIcons"
style={[styles.sendIcon]}
/>
</Button>
<Input
multiline
style={styles.userStatusMessage}
placeholder="Type a message ..."
placeholderTextColor={LIGHT_GRAY}
value={message}
onChangeText={text => {
setMessage(text);
}}
/>
<Button
icon
rounded
large
style={styles.sendStatusIconView}
onPress={() => {
onSendMessage(message);
setMessage('');
}}>
<Icon
name={'send'}
type="MaterialCommunityIcons"
style={styles.sendIcon}
/>
</Button>
</View>
);
};
return (
<KeyboardAvoidingView style={{paddingBottom: keyboardPadding}}>
<View style={styles.parentView}>
{isStatus ? getStatusInput() : getChatRoomInput()}
</View>
</KeyboardAvoidingView>
);
}
Example #16
Source File: ChatListView.js From WhatsApp-Clone with MIT License | 4 votes |
ChatListView = ({navigation}) => {
var [state, dispatch] = useReducer(chatListReducer, initialChatListState);
var {chatList, chatItem, refresh, userId} = state;
useFocusEffect(
React.useCallback(() => {
getLatestChats();
}, []),
);
useEffect(() => {
listenSocket();
}, []);
useEffect(() => {
if (refresh) {
getLatestChats();
}
}, [refresh]);
useEffect(() => {
// console.log('Chat List Changed == ', JSON.stringify(chatList));
if (chatItem != '') {
renderChats();
}
}, [chatItem]);
async function getUserId() {
const userId = await getLocalData(constants.USER_ID);
dispatch({type: constants.USER_ID, payload: userId});
return userId;
}
const getLatestChats = async () => {
await getUserId();
getChatList()
.then(res => {
// console.log('RESPONSE => ' + JSON.stringify(res.data.data));
if (res.status === 200) {
dispatch({type: CHAT_LIST, payload: res.data.data});
}
dispatch({type: REFRESH, payload: false});
})
.catch(error => {
console.log('ERROR ', error);
});
};
async function renderChats() {
let chatArray = chatList;
console.log("Message CHAT Received => ", JSON.stringify(chatItem));
var isMatch = false;
if (chatArray.length > 0) {
for (let i = 0; i < chatArray.length; i++) {
const element = chatArray[i];
if (chatItem && element.roomId === chatItem.roomId) {
// Increment unread count
chatItem = await calcUnreadCount(chatItem, element.chatUnreadCount);
// Since chat item received is an object to convert it to array and they re initialise
// if (chatItem.chat.length <= 0) {
chatItem.chat = [chatItem.chat];
// }
console.log("Selected Chat Received => ", JSON.stringify(chatItem));
chatArray[i] = chatItem;
isMatch = true;
break;
}
}
if (!isMatch && chatItem.chatUnreadCount.type != 'reset') {
// Increment unread count
chatItem = await calcUnreadCount(chatItem, 0);
// Since chat item received is an object to convert it to array and they re initialise
// if (chatItem.chat.length <= 0) {
chatItem.chat = [chatItem.chat];
// }
console.log("Selected Chat Received => ", JSON.stringify(chatItem));
chatArray.push(chatItem);
}
console.log("Message CHAT AFTER Received => ", JSON.stringify(chatItem));
dispatch({ type: CHAT_LIST, payload: chatArray });
console.log(
`FINAL CHAT ARRAY ${refresh} => `,
"JSON.stringify(chatArray)"
);
} else {
// For new chat
if (chatItem.chatUnreadCount.type === "add") {
dispatch({ type: REFRESH, payload: true });
}
}
}
function listenSocket() {
// socket.removeListener(constants.CHAT_LIST);
socket.on(constants.CHAT_LIST, chatItem => {
dispatch({type: CHAT_ITEM, payload: chatItem});
});
}
// function calcUnreadCount(chatItem, element) {
// // const userId = await getLocalData(constants.USER_ID);
// if (element.chatUnreadCount.length > 0) {
// for (let index = 0; index < element.chatUnreadCount.length; index++) {
// const data = element[index];
// if (data.userid != userId) {
// if (chatItem.chatUnreadCount.type === 'reset') {
// data.count = 0;
// } else if (chatItem.chatUnreadCount.type === 'add') {
// data.count = data.count + 1;
// }
// chatItem.chatUnreadCount = element.chatUnreadCount;
// break;
// }
// }
// }
// return chatItem;
// }
function calcUnreadCount(chatItem, originalCount) {
// const userId = await getLocalData(constants.USER_ID);
if (chatItem.chatUnreadCount.userId != userId) {
if (chatItem.chatUnreadCount.type === 'reset') {
chatItem.chatUnreadCount = 0;
} else if (chatItem.chatUnreadCount.type === 'add') {
chatItem.chatUnreadCount = originalCount ? originalCount + 1 : 1;
} else {
chatItem.chatUnreadCount = 0;
}
} else if (chatItem.chatUnreadCount.type === 'reset') {
chatItem.chatUnreadCount = 0;
} else {
chatItem.chatUnreadCount = originalCount;
}
return chatItem;
}
return (
<View style={{flex: 1}}>
{chatList.length === 0 && <EmptyComponent message={'No Chats Found'} />}
<FlatList
data={chatList}
extraData={refresh}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={() => {
return <_Divider />;
}}
renderItem={({item, index}) => {
return (
<ChatListItem item={item} navigation={navigation} userId={userId} />
);
}}
/>
<Button
active={true}
rounded
style={styles.btnView}
onPress={() =>
navigation.navigate(NAV_TYPES.CONTACTS_SCREEN, {chatList})
}>
<Image source={CHAT} style={styles.thumbView} />
</Button>
</View>
);
}
Example #17
Source File: CameraView.js From WhatsApp-Clone with MIT License | 4 votes |
CameraView = ({navigation, onScanQrCode, isScanCode}) => {
var [state, dispatch] = useReducer(statusReducer, statusState);
var {loading, isFlashEnabled, isFrontCam} = state;
const [imageClicked, setImageClicked] = useState('');
var cameraRef = useRef('');
const LoadingView = () => <LoadingComponent />;
function performAction(camera) {
if (isScanCode) {
onScanQrCode();
} else {
takePicture(camera);
}
}
const takePicture = async function(camera) {
const options = {
// quality: 0.5,
base64: true,
quality: 0.6,
orientation: RNCamera.Constants.Orientation.auto,
pauseAfterCapture: true,
fixOrientation: true,
};
const data = await cameraRef.current.takePictureAsync(options);
// cameraRef.current.pausePreview();
// console.log(data.uri);
setImageClicked(data.uri);
};
function toggleViews(type) {
switch (type) {
case TOGGLE_CAMERA:
dispatch({type: TOGGLE_CAMERA, payload: !isFrontCam});
break;
case TOGGLE_FLASH:
dispatch({type: TOGGLE_FLASH, payload: !isFlashEnabled});
break;
}
}
return (
<Root>
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<RNCamera
autoFocus='on'
// autoFocusPointOfInterest
ref={cameraRef}
useCamera2Api
onTouchStart={Keyboard.dismiss}
style={styles.preview}
type={
isFrontCam
? RNCamera.Constants.Type.front
: RNCamera.Constants.Type.back
}
flashMode={
isFlashEnabled
? RNCamera.Constants.FlashMode.on
: RNCamera.Constants.FlashMode.off
}
barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
onBarCodeRead={result => {
if (isScanCode) {
// console.log(result.data);
onScanQrCode(result.data)
}
}}
androidCameraPermissionOptions={{
title: 'Permission to use camera',
message: 'We need your permission to use your camera',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
androidRecordAudioPermissionOptions={{
title: 'Permission to use audio recording',
message: 'We need your permission to use your audio',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}>
{({camera, status, recordAudioPermissionStatus}) => {
if (status !== 'READY') return <LoadingView />;
if (Platform.OS === 'ios') {
return (
<KeyboardAvoidingView
behavior={'padding'}
onTouchStart={Keyboard.dismiss}
style={{width: '100%', height: '100%'}}>
{getMainView(camera)}
</KeyboardAvoidingView>
);
} else {
return getMainView(camera);
}
}}
</RNCamera>
</View>
</SafeAreaView>
</Root>
);
function getMainView(camera) {
return (
<View style={{width: '100%', height: '100%'}}>
<View style={styles.headerView}>
<BorderlessButton
style={styles.buttonStyle}
onPress={() => navigation.goBack()}>
<Icon
name={Platform.OS === 'ios' ? 'ios-arrow-back' : 'md-arrow-back'}
type="Ionicons"
style={styles.leftIcon}
/>
</BorderlessButton>
<View
style={{
flexDirection: 'row',
justifyContent: 'flex-end',
}}>
<BorderlessButton
style={styles.buttonStyle}
onPress={() => toggleViews(TOGGLE_CAMERA)}>
<Icon
name={
Platform.OS === 'ios'
? isFrontCam
? 'md-reverse-camera'
: 'md-reverse-camera'
: isFrontCam
? 'md-reverse-camera'
: 'md-reverse-camera'
}
type="Ionicons"
style={styles.leftIcon}
/>
</BorderlessButton>
<BorderlessButton
style={styles.buttonStyle}
onPress={() => toggleViews(TOGGLE_FLASH)}>
<Icon
name={
Platform.OS === 'ios'
? isFlashEnabled
? 'ios-flash'
: 'ios-flash-off'
: isFlashEnabled
? 'md-flash'
: 'md-flash-off'
}
type="Ionicons"
style={styles.leftIcon}
/>
</BorderlessButton>
</View>
</View>
{imageClicked === '' && !isScanCode && (
<Button
rounded
onPress={() => performAction(camera)}
style={styles.capture}>
<Icon
name="camera"
type="MaterialCommunityIcons"
style={styles.sendIcon}
/>
{/* <Text style={{fontSize: 14}}> SNAP </Text> */}
</Button>
)}
{imageClicked != '' && (
<View style={styles.bottomView}>
<ChatTextInput
isStatus
onSendMessage={status => {
dispatch({type: LOADING, payload: true});
uploadStatus(imageClicked, status, navigation, dispatch);
}}
onResetClick={() => {
// cameraRef.current.resumePreview();
setImageClicked('');
}}
/>
</View>
)}
{loading && <LoadingView />}
</View>
);
}
}
Example #18
Source File: ReportForm.js From pandoa with GNU General Public License v3.0 | 4 votes |
function ReportForm({ reportCaseTrigger, positions }) {
const { control, handleSubmit, errors } = useForm();
const onSubmit = data => {
Alert.alert("Data submitted");
reportCaseTrigger(positions);
// Alert.alert("Form Data", JSON.stringify(data), positions.length);
};
return (
<View>
<Form>
<Text style={styles.hintText}>
On this page you can report if you have got an infection. Please enter
your details below
</Text>
<View style={styles.inputWrapper}>
<Item>
<Text>Picker</Text>
<Controller
as={e => {
console.log(e);
return (
<Picker
note
mode="dropdown"
style={{ width: 120 }}
selectedValue={"key3"}
onValueChange={() => {}}
>
<Picker.Item label="Wallet" value="key0" />
<Picker.Item label="ATM Card" value="key1" />
<Picker.Item label="Debit Card" value="key2" />
<Picker.Item label="Credit Card" value="key3" />
<Picker.Item label="Net Banking" value="key4" />
</Picker>
);
}}
control={control}
name="firstName"
onChange={args => args[0].nativeEvent.text}
onChange={e => {
return "key1";
// Place your logic here
return selected;
}}
rules={{ required: true }}
defaultValue=""
placeholder="Username"
/>
</Item>
{errors.firstName && <Text>This is required.</Text>}
<Item>
<Controller
as={Input}
control={control}
name="lastName"
onChange={args => args[0].nativeEvent.text}
defaultValue=""
placeholder="Password"
/>
</Item>
</View>
<Text style={styles.hintText}>
Enter a contact phone number. This can be yours or a doctors phone
number.
</Text>
<View style={styles.inputWrapper}>
<Item>
<Label>Contact phone number</Label>
<Controller
as={Input}
control={control}
name="contact_phone"
onChange={args => args[0].nativeEvent.text}
defaultValue=""
/>
</Item>
</View>
<Text style={styles.hintText}>Enter information for you contact.</Text>
<View style={styles.inputWrapper}>
<Item style={styles.input}>
<Label>Contact information</Label>
<Controller
as={Input}
control={control}
name="contact_information"
onChange={args => args[0].nativeEvent.text}
defaultValue=""
placeholder="Contact information"
/>
</Item>
</View>
</Form>
{/*
<Form>
<Item>
<Input placeholder="Username" />
</Item>
<Item last>
<Input placeholder="Password" />
</Item>
<Button primary onPress={reportButton}>
<Text>Submit data</Text>
</Button>
</Form>*/}
<View style={styles.submitWrapper}>
<Button primary onPress={handleSubmit(onSubmit)}>
<Text>Submit</Text>
</Button>
</View>
</View>
);
}
Example #19
Source File: UserProfileScreen.js From SocialApp-React-Native with MIT License | 4 votes |
UserProfileScreen = (props) => {
const { route } = props;
const loggedInUserId = useSelector(state => state.auth.user._id);
const allUsers = useSelector(state => state.users.allUsers);
const loggedInUser = allUsers.filter(u => u._id === loggedInUserId)[0];
let userId;
if(route.params && route.params.userId){
userId = route.params.userId;
} else {
userId = useSelector(state => state.auth.user._id);
}
const users = useSelector(state => state.users.allUsers);
const posts = useSelector(state => state.posts.allPosts);
const currUser = users.filter(u => u._id === userId)[0];
const currUserPosts = posts.filter(p => p.postedBy._id === userId);
const [isRefreshing,setIsRefreshing] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isFollowLoading, setIsFollowLoading] = useState(false);
const [imageUri, setImageUri] = useState('');
const dispatch = useDispatch();
const loadUsers = useCallback(async () => {
setIsRefreshing(true);
try {
await dispatch(usersActions.fetchUsers());
await dispatch(postsActions.fetchPosts());
} catch (err) {
console.log(err);
}
setIsRefreshing(false);
}, [dispatch, setIsLoading]);
const onImageErrorHandler = () => {
setImageUri(ENV.defaultImageUri)
}
const checkFollow = (userId) => {
const isFollowed = loggedInUser.following.filter(f => f._id === userId).length !== 0;
return isFollowed;
}
const followUserHandler = async () => {
let user = {...currUser};
delete user.created;
delete user.followers;
delete user.following;
// setIsFollowLoading(true);
if(checkFollow(user._id)){
showMessage({
message: `Your have unfollowed ${user.name}.`,
type: "warning",
duration: 3000,
icon: { icon: "warning", position: 'left' }
});
await dispatch(usersActions.unfollowUser(user))
} else {
showMessage({
message: `Your are now following ${user.name}.`,
type: "success",
duration: 3000,
icon: { icon: "success", position: 'left' }
});
await dispatch(usersActions.followUser(user))
}
// setIsFollowLoading(false);
}
const renderSectionOne = () => {
if(currUserPosts.length === 0 ){
return(
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', borderTopColor: '#c2c2c2', borderTopWidth: 1 }} >
<Text style={{ fontSize: 20, fontWeight: 'bold', marginTop: 25 }} >No Posts</Text>
{ currUser._id === loggedInUserId && (
<Button
style={{ backgroundColor: Colors.brightBlue, padding: 10, borderRadius: 25, marginTop: 15 }}
onPress={() => props.navigation.navigate('AddPost')}
>
<Text style={{ color: '#fff' }} >Create Post</Text>
</Button>
) }
</View>
)
}
return currUserPosts.map((post, index) => {
return (
<TouchableOpacity
key={index}
onPress={() => props.navigation.navigate('UserPosts', { userId: userId, postIndex: index, fromUserProfile: true })}
>
<View style={[{ width: (width) / 3 }, { height: (width) / 3 }, { marginBottom: 2 }, index % 3 !== 0 ? { paddingLeft: 2 } : { paddingLeft: 0 }]}>
<Image
style={{
flex: 1,
alignSelf: 'stretch',
width: undefined,
height: undefined,
backgroundColor: '#c2c2c2'
}}
source={
post.updated ? (
{ uri: `${ENV.apiUrl}/post/photo/${post._id}?${new Date(post.updated)}` }
) : (
{ uri: `${ENV.apiUrl}/post/photo/${post._id}` }
)
}
/>
</View>
</TouchableOpacity>
)
})
}
const renderSection = () => {
return (
<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
{renderSectionOne()}
</View>
)
}
if(isLoading){
return (
<View style={styles.centered} >
<ActivityIndicator size='large' color={Colors.primary} />
</View>
);
}
let TouchableComp = TouchableOpacity;
if(Platform.OS === 'android' && Platform.Version >= 21){
TouchableComp = TouchableNativeFeedback;
}
return (
<Container style={styles.container} >
<Content
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={loadUsers} />
}
>
<View style={{ paddingTop: 20 }}>
{/** User Photo Stats**/}
<View style={{ flexDirection: 'row' }}>
{/**User photo takes 1/3rd of view horizontally **/}
<View
style={{ flex: 1, alignItems: 'center', justifyContent: 'flex-start' }}>
<Image
source={{ uri: imageUri || `${ENV.apiUrl}/user/photo/${currUser._id}?${new Date(currUser.updated)}` }}
onError={onImageErrorHandler}
style={{ width: 75, height: 75, borderRadius: 37.5, backgroundColor: "#c2c2c2" }}
/>
</View>
{/**User Stats take 2/3rd of view horizontally **/}
<View style={{ flex: 3 }}>
{/** Stats **/}
<View
style={{
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'flex-end'
}}
>
<View style={{ alignItems: 'center' }}>
<TouchableComp
background={ Platform.OS === 'ios' ? undefined : TouchableNativeFeedback.Ripple('#c2c2c2', true) }
onPress={() => props.navigation.navigate(
'UserPosts',
{ userId: userId, postIndex: 0, fromUserProfile: true }
)}
>
<View style={{ justifyContent: 'center', alignItems: 'center' }} >
<Text style={{ fontSize: 18 }} >{currUserPosts.length}</Text>
<Text style={{ fontSize: 12, color: 'grey' }}>Posts</Text>
</View>
</TouchableComp>
</View>
<View style={{ alignItems: 'center' }}>
<TouchableComp
background={ Platform.OS === 'ios' ? undefined : TouchableNativeFeedback.Ripple('#c2c2c2', true) }
onPress={() => props.navigation.navigate(
'UserStats',
{ activeTab: 0, currUser: currUser }
)}
>
<View style={{ justifyContent: 'center', alignItems: 'center' }} >
<Text style={{ fontSize: 18 }} >{currUser.followers.length}</Text>
<Text style={{ fontSize: 12, color: 'grey' }}>Followers</Text>
</View>
</TouchableComp>
</View>
<View style={{ alignItems: 'center' }}>
<TouchableComp
background={ Platform.OS === 'ios' ? undefined : TouchableNativeFeedback.Ripple('#c2c2c2', true) }
onPress={() => props.navigation.navigate(
'UserStats',
{ activeTab: 1, currUser: currUser }
)}
>
<View style={{ justifyContent: 'center', alignItems: 'center' }} >
<Text style={{ fontSize: 18 }} >{currUser.following.length}</Text>
<Text style={{ fontSize: 12, color: 'grey' }}>Following</Text>
</View>
</TouchableComp>
</View>
</View>
{/**
* Edit profile and Settings Buttons **/}
{ userId === loggedInUserId ? (
<View style={{ alignItems: 'flex-start', paddingTop: 10 }}>
<View
style={{ flexDirection: 'row' }}>
<Button
onPress={() => props.navigation.navigate('EditProfile')}
bordered
dark
style={{ flex: 1, marginLeft: 10, marginRight: 10, justifyContent: 'center', height: 30 }}
>
<Text>Edit Profile</Text>
</Button>
</View>
</View>
) : (
<View style={{ flexDirection: 'row', alignItems: 'flex-start', paddingTop: 10 }}>
<TouchableOpacity
style={{ flexDirection: 'row' }}>
<Button
onPress={followUserHandler}
bordered
dark
style={{ flex: 2, marginLeft: 10, marginRight: 10, justifyContent: 'center', height: 30 }}
>
{ checkFollow(currUser._id) ? (
<>
{ isFollowLoading ? (
<ActivityIndicator size="small" color="#fff" />
) : (
<Text style={{ color: 'black' }} >Unfollow</Text>
) }
</>
) : (
<>
{ isFollowLoading ? (
<ActivityIndicator size="small" color="#fff" />
) : (
<Text style={{ color: 'black' }} >Follow</Text>
) }
</>
) }
</Button>
</TouchableOpacity>
</View>
) }
{/**End edit profile**/}
</View>
</View>
<View style={{ paddingBottom: 10, paddingTop: 10 }}>
<View style={{ paddingHorizontal: 10 }} >
<Text style={{ fontWeight: 'bold', fontSize: 18 }}>
{currUser.name + " "}
{
VerifiedUser.verifiedUsersId.includes(currUser._id) && <Octicons name="verified" size={20} color={Colors.brightBlue} />
}
</Text>
{ currUser.about && (
<Text>{currUser.about} </Text>
) }
<Text>{currUser.email}</Text>
</View>
</View>
</View>
<View>
{renderSection()}
</View>
</Content>
</Container >
);
}
Example #20
Source File: FindPeopleScreen.js From SocialApp-React-Native with MIT License | 4 votes |
FindPeopleScreen = (props) => {
const findPeopleUsers = useSelector(state => state.users.findPeople);
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [error, setError] = useState();
const [searchText, setSearchText] = useState('');
const [data, setData] = useState([]);
const dispatch = useDispatch();
const loadFindPeople = useCallback(async () => {
setError(null);
setIsRefreshing(true);
try {
const result = await dispatch(usersActions.fetchFindPeopleUsers());
let verifiedUsers = result.filter(e => VerifiedUser.verifiedUsersId.includes(e._id));
let otherUsers = result.filter(e => !VerifiedUser.verifiedUsersId.includes(e._id));
let updatedResult = [...verifiedUsers, ...otherUsers];
setData(updatedResult);
} catch (err) {
setError(err.message);
}
setIsRefreshing(false);
}, [dispatch, setIsLoading, setError])
useEffect(() => {
setIsLoading(true);
loadFindPeople()
.then(() => {
setIsLoading(false);
});
}, [dispatch, loadFindPeople])
// useEffect(() => {
// const unsubscribe = props.navigation.addListener('focus', e => {
// setSearchText('');
// setData(findPeopleUsers);
// });
// return () => {
// unsubscribe();
// };
// }, [])
const handleSearchTextChange = (text) => {
setSearchText(text);
if(text !== ''){
let filteredData = []
let currData = findPeopleUsers;
filteredData = currData.filter(item => {
const lc = item.name.toLowerCase();
const lcEmail = item.email.toLowerCase();
text = text.toLowerCase();
return lc.includes(text) || lcEmail.includes(text);
});
setData(filteredData);
} else {
setData(findPeopleUsers);
}
}
const followHandlerForData = (id) => {
//follow handler to remove item from search data i.e. data state
let searchData = data;
searchData = searchData.filter(i => i._id !== id);
setData(searchData);
}
if(error){
return (
<View style={styles.centered} >
<Text>An error occured.</Text>
<Button onPress={loadFindPeople} color={Colors.primary} >
<Text>Try again</Text>
</Button>
</View>
);
}
if(isLoading){
return (
<View style={styles.centered} >
<ActivityIndicator size='large' color={Colors.primary} />
</View>
);
}
return (
<Container style={{ backgroundColor: '#fff' }} >
<Header style={{ backgroundColor: Colors.brightBlue }} searchBar rounded>
<Item>
<Icon name="ios-search" />
<Input
value={searchText}
onChangeText={(text) => handleSearchTextChange(text)}
placeholder={`Search by name or email...`}
/>
<Text>{data.length}</Text>
<Icon name="ios-people" />
</Item>
</Header>
{ data.length === 0 && (
<View style={styles.centered}>
<Text style={{ fontSize: 18, margin: 10 }} >No users found.</Text>
<Text>Either you are already following the user</Text>
<Text>or no user exists with that name.</Text>
</View>
) }
<FlatList
style={styles.list}
refreshing={isRefreshing}
onRefresh={loadFindPeople}
contentContainerStyle={styles.listContainer}
data={data}
horizontal={false}
numColumns={2}
keyExtractor={(item) => {
return item._id;
}}
renderItem={({ item }) => (
<UserList item={item} followHandler={followHandlerForData} />
)}
/>
</Container>
);
}
Example #21
Source File: MakeTransaction.js From web3-react-native with MIT License | 4 votes |
MakeTransaction = ({ onPressSubmit, ...extraProps }) => {
const [toAddress, setToAddress] = useState("0x19e03255f667bdfd50a32722df860b1eeaf4d635");
const [amount, setAmount] = useState("1");
const [units, setUnits] = useState("wei");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
return (
<Container>
<Content>
<Form>
<Item>
<Label
children="Address:"
/>
<Input
onChangeText={setToAddress}
value={toAddress}
/>
</Item>
<Item
>
<Label
children="Amount:"
/>
<Input
onChangeText={setAmount}
value={amount}
/>
</Item>
<Item
last
>
<Label
children="Units:"
/>
<Picker
onValueChange={setUnits}
selectedValue={units}
>
<Picker.Item label="Wei" value="wei" />
<Picker.Item label="Kwei" value="kwei" />
<Picker.Item label="Mwei" value="mwei" />
<Picker.Item label="Gwei" value="gwei" />
<Picker.Item label="Finney" value="finney" />
<Picker.Item label="Ether" value="eth" />
</Picker>
</Item>
</Form>
<View
style={styles.errorContainer}
>
{(!!error) && (
<Text
style={styles.error}
children={error.message}
/>
)}
</View>
<View
style={styles.buttonContainer}
>
<Button
disabled={loading}
style={styles.button}
onPress={e => Promise
.resolve()
.then(() => [
setLoading(true),
])
.then(() => onPressSubmit(e, toAddress, amount, units))
.then(() => setLoading(false))
.catch(
(e) => {
setError(e);
setLoading(false);
},
)}
primary
rounded
>
{(!!loading) && (
<Spinner
size={20}
/>
)}
<Text
children="Send"
/>
</Button>
</View>
</Content>
</Container>
);
}
Example #22
Source File: index.js From aws-appsync-refarch-offline with MIT No Attribution | 4 votes |
Checkout = (props) => {
const order = useSelector(state => state.order);
const dispatch = useDispatch();
async function submitOrder() {
const now = new Date().toISOString();
const newOrder = await DataStore.save(
new Order({
total: order.total,
subtotal: order.subtotal,
tax: order.tax,
createdAt: now,
})
);
const promises = order.lineItems.map(lineItem => {
return DataStore.save(
new LineItem({
qty: lineItem.qty,
description: lineItem.description,
price: lineItem.price,
total: lineItem.total,
order: newOrder, // associate to order
product: lineItem.product, // associate to product
})
);
});
await Promise.all(promises);
}
async function checkoutBtnHandler() {
await submitOrder();
dispatch(startNewOrder());
props.navigation.goBack();
}
const lineItemList = order.lineItems.map(lineItem => (
<ListItem icon key={lineItem.sku}>
<Left>
<Text>{lineItem.qty}</Text>
</Left>
<Body>
<Text>{lineItem.description}</Text>
</Body>
<Right>
<Text>${lineItem.total.toFixed(2)}</Text>
</Right>
</ListItem>
));
return (
<Container>
<Content>
<Text style={styles.totalTxt}>TOTAL</Text>
<Text style={styles.totalQty}>${order.total.toFixed(2)}</Text>
<List>
<ListItem itemDivider>
<Text> </Text>
</ListItem>
{lineItemList}
<ListItem itemDivider>
<Text> </Text>
</ListItem>
<ListItem>
<Body>
<Text style={styles.subtotalsTxt}>Subtotal</Text>
</Body>
<Right>
<Text>${order.subtotal.toFixed(2)}</Text>
</Right>
</ListItem>
<ListItem>
<Body>
<Text style={styles.subtotalsTxt}>Tax</Text>
</Body>
<Right>
<Text>${order.tax.toFixed(2)}</Text>
</Right>
</ListItem>
<ListItem>
<Body>
<Text style={styles.subtotalsTxt}>Total</Text>
</Body>
<Right>
<Text>${order.total.toFixed(2)}</Text>
</Right>
</ListItem>
</List>
<Button block info style={styles.checkoutBtn} onPress={checkoutBtnHandler} disabled={order.lineItems.length === 0}>
<Text style={styles.checkoutTxt}>Checkout</Text>
</Button>
</Content>
</Container>
);
}