react-native-paper#Snackbar JavaScript Examples
The following examples show how to use
react-native-paper#Snackbar.
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: MapView.js From Legacy with Mozilla Public License 2.0 | 6 votes |
export default function Map(props) {
const theme = useSelector(i => i.themes[i.theme]);
const appleMaps = useSelector(i => i.settings.appleMaps);
const center = {
latitude: 0,
longitude: 0,
latitudeDelta: 90,
longitudeDelta: 90
}
const mapRef = React.useRef(null);
const [locError, setLocError] = React.useState(false);
async function getLocation() {
var { status } = await Location.requestPermissionsAsync();
if (status !== "granted") {
setLocError(true);
return;
}
try {
var loc = await Location.getCurrentPositionAsync({})
mapRef.current.animateToRegion({
latitude: loc.coords.latitude,
longitude: loc.coords.longitude,
latitudeDelta: 0.5,
longitudeDelta: 0.5,
});
} catch (e) {
setLocError(true);
}
}
return <View style={{ flex: 1 }}>
<MapView
ref={mapRef}
initialRegion={center}
region={props.region}
clusteringEnabled={props.markers?.length>60}
provider={appleMaps?null:"google"}
customMapStyle={theme.mapStyle}
style={{ flex: 1 }}
onRegionChangeComplete={(region)=>{
props.onRegionChange?.({
latitude: region.latitude,
longitude: region.longitude,
latitudeDelta: region.latitudeDelta,
longitudeDelta: region.longitudeDelta
})
}}
>
{(props.circles||[]).map(i => <Circle
key={i.id}
center={{ latitude: i.lat, longitude: i.lng }}
radius={i.radius}
fillColor={i.fill}
strokeColor={i.stroke}
/>)}
{props.markers?.map(i => <MapMarker key={i.id} {...i} />)}
</MapView>
<FAB
style={{ position: "absolute", top: 8, left: 8, backgroundColor: theme.navigation.bg }}
color={theme.navigation.fg}
small
icon={true ? "crosshairs-gps" : "crosshairs"}
onPress={getLocation}
/>
<Snackbar
visible={locError}
onDismiss={() => setLocError(false)}
duration={2000}
>
{typeof locError == "string" ? locError : "Failed retreiving location"}
</Snackbar>
</View>
}
Example #2
Source File: index.js From puente-reactnative-collect with MIT License | 6 votes |
PopupError = ({ error, setError, errorMessage }) => {
useEffect(() => {
setVisible(error);
}, [error]);
const [visible, setVisible] = useState(false);
const dismissSnackBar = () => {
setVisible(false);
setError(false);
};
return (
<View>
<Snackbar
visible={visible}
onDismiss={dismissSnackBar}
duration={6000}
style={{
backgroundColor: 'red',
fontSize: 130
}}
>
<Text style={{ fontSize: 16, fontWeight: 'bold' }}>
{I18n.t(errorMessage)}
</Text>
</Snackbar>
</View>
);
}
Example #3
Source File: index.js From puente-reactnative-collect with MIT License | 6 votes |
PopupSuccess = ({ success, setSuccess, submittedForms }) => {
useEffect(() => {
setVisible(success);
}, [success]);
const [visible, setVisible] = useState(false);
const dismissSnackBar = () => {
setVisible(false);
setSuccess(false);
};
return (
<View>
<Snackbar
visible={visible}
onDismiss={dismissSnackBar}
duration={6000}
style={{
backgroundColor: 'green',
fontSize: 130
}}
>
<Text style={{ fontSize: 16, fontWeight: 'bold' }}>
{submittedForms}
{' '}
Records Successfully Stored!
</Text>
</Snackbar>
</View>
);
}
Example #4
Source File: index.js From puente-reactnative-collect with MIT License | 5 votes |
ErrorPicker = ({ formikProps, inputs }) => {
const { errors, isSubmitting } = formikProps;
const [formErrors, setFormErrors] = useState([]);
const [visible, setVisible] = useState(false);
const keysToLabel = (keys) => {
let label = [];
keys.forEach((key) => {
inputs.forEach((input) => {
if (key === input.formikKey) {
label = label.concat([I18n.t(input.label)]);
} else if (input.fieldType === 'multiInputRowNum') {
input.options.forEach((option) => {
if (key === option.value) {
label = label.concat(I18n.t(option.label));
}
});
}
});
});
setFormErrors(label.join(', '));
};
useEffect(() => {
if (Object.keys(errors).length > 0) {
setVisible(true);
} else {
setVisible(false);
}
keysToLabel(Object.keys(errors));
}, [isSubmitting]);
const dismissSnackBar = () => setVisible(false);
return (
<View>
<Snackbar
visible={visible}
onDismiss={dismissSnackBar}
duration={8500}
style={{
backgroundColor: 'red',
fontSize: 130
}}
>
<Text style={{ fontSize: 16, fontWeight: 'bold' }}>
{I18n.t('errorPicker.invalidFields')}
{'\n\n'}
{formErrors}
</Text>
</Snackbar>
</View>
);
}
Example #5
Source File: MapView.web.js From Legacy with Mozilla Public License 2.0 | 4 votes |
function WebMap(props) {
var theme = useSelector(i => i.themes[i.theme])
var [center,setCenter] = React.useState({lat:0,lng:0});
var [map,setMap] = React.useState(null)
var [locError, setLocError] = React.useState(false);
async function getLocation() {
try {
var loc = await Location.getCurrentPositionAsync({})
map.panTo({
lat: loc.coords.latitude,
lng: loc.coords.longitude
});
map.setZoom(10);
} catch(e) {
setLocError(true);
}
}
return (
<LoadScript
googleMapsApiKey={key}
version={version}
libraries={libraries}
>
<GoogleMap
zoom={1}
center={props.center||center}
options={{
streetViewControl: false,
zoomControl: false,
scaleControl: true,
rotateControl: false,
clickableIcons: false,
mapTypeControl: false,
fullscreenControl: false,
controlSize: 32,
gestureHandling: "greedy",
mapTypeControlOptions: {
mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain', 'styled_map']
},
mapId: theme.dark?'1e47783ba0e84c45':'f5056005d4606f72'
}}
mapContainerStyle={{flex: 1}}
onLoad={(m)=>setMap(m)}
onCenterChanged={()=>{
if(map) {
if(center.lat!==map.center.lat()||center.lng!==map.center.lng()) setCenter({
lat: map.center.lat(),
lng: map.center.lng()
})
props.onRegionChange?.({
latitude: map.center.lat(),
longitude: map.center.lng()
})
}
}}
>
<FAB
style={{position: "absolute", top: 8, left: 8, backgroundColor: theme.navigation.bg}}
color={theme.navigation.fg}
small
icon={true?"crosshairs-gps":"crosshairs"}
onPress={getLocation}
/>
<FAB
style={{position: "absolute", bottom: 22, right: 8, backgroundColor: theme.navigation.bg}}
color={theme.navigation.fg}
small
icon={"minus"}
onPress={()=>map.setZoom(map.getZoom()-1)}
/>
<FAB
style={{position: "absolute", bottom: 70, right: 8, backgroundColor: theme.navigation.bg}}
color={theme.navigation.fg}
small
icon={"plus"}
onPress={()=>map.setZoom(map.getZoom()+1)}
/>
<Snackbar
visible={locError}
onDismiss={()=>setLocError(false)}
duration={2000}
>
Couldn't retrieve location
</Snackbar>
<MarkerRenderer {...props} />
{props.circles?.map(i=><Circle
radius={i.radius}
center={{ lat: i.lat, lng: i.lng }}
options={{
fillColor: i.fill,
fillOpacity: 1,
strokeColor: i.stroke,
strokeOpacity: 1,
}}
/>)}
</GoogleMap>
</LoadScript>
)
}
Example #6
Source File: model.js From Reminder-App with MIT License | 4 votes |
export default function ({ selecteditem, hide_model, edit }) {
const [text, settext] = useState(selecteditem.text);
const [time, settime] = useState(new Date(selecteditem.Date));
const [mode, setMode] = useState("date");
const [show, setShow] = useState(false);
const { colors } = useTheme();
const [visible, setVisible] = useState(false);
const onToggleSnackBar = () => setVisible(!visible);
const onDismissSnackBar = () => setVisible(false);
if (show) {
return (
<DateTimePicker
minimumDate={new Date(Date.now())}
value={time}
mode={mode}
display="default"
onChange={(event, date) => {
if (event.type == "dismissed") {
setShow(false);
return;
}
let tep = new Date(Date.now());
if (tep.getTime() / 1000 - date.getTime() / 1000 > 1) {
setShow(false);
onToggleSnackBar();
return;
}
settime(date);
setShow(false);
}}
style={{ width: 320, backgroundColor: "gray" }} //add this
/>
);
}
return (
<View
style={{
flex: 1,
justifyContent: "center",
}}
>
<TouchableOpacity
onPress={() => hide_model()}
style={{
alignSelf: "flex-end",
marginHorizontal: 10,
marginBottom: 10,
}}
>
<AntDesign name="closecircleo" size={30} color={colors.text} />
</TouchableOpacity>
<View style={[styles.model, { backgroundColor: colors.tab }]}>
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
flex: 1,
}}
>
<View
style={{
flex: 1,
marginTop: 7,
marginHorizontal: 3,
}}
>
<TextInput
maxLength={100}
multiline
numberOfLines={2}
selectTextOnFocus={text == "Tap to edit"}
onChangeText={(text) => settext(text)}
value={text}
style={[styles.text, { color: colors.text }]}
/>
<Text
style={[
styles.text,
{ fontSize: 14, marginTop: 15, color: colors.text },
]}
>
{`${moment(time).format("hh:mm a")}, ${
moment(time).format("Do ") + moment(time).format("MMM YYYY")
}`}
</Text>
</View>
<View style={[styles.sep]} />
<View style={{ flexDirection: "column" }}>
<Text
style={[
styles.text,
{ fontSize: 10, alignSelf: "center", color: colors.text },
]}
>
Tap to change
</Text>
<TouchableOpacity
style={styles.button}
onPress={() => {
setMode("date");
setShow(true);
}}
>
<Text style={[styles.text, { fontSize: 16, color: colors.text }]}>
Date
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => {
setMode("time");
setShow(true);
}}
>
<Text style={[styles.text, { fontSize: 16, color: colors.text }]}>
Time
</Text>
</TouchableOpacity>
</View>
</View>
</View>
<TouchableOpacity
onPress={() => {
edit({ text, selecteditem, time: moment(time) });
hide_model();
}}
style={styles.button}
>
<Text style={[styles.text, { fontSize: 18, color: colors.text }]}>
Save
</Text>
</TouchableOpacity>
<Snackbar
visible={visible}
onDismiss={onDismissSnackBar}
action={{
label: "OK",
onPress: () => {
onToggleSnackBar();
},
}}
>
Invaild Date or Time
</Snackbar>
</View>
);
}
Example #7
Source File: Register.js From InstagramClone with Apache License 2.0 | 4 votes |
export default function Register(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [username, setUsername] = useState('');
const [isValid, setIsValid] = useState(true);
const onRegister = () => {
if (name.lenght == 0 || username.lenght == 0 || email.length == 0 || password.length == 0) {
setIsValid({ bool: true, boolSnack: true, message: "Please fill out everything" })
return;
}
if (password.length < 6) {
setIsValid({ bool: true, boolSnack: true, message: "passwords must be at least 6 characters" })
return;
}
if (password.length < 6) {
setIsValid({ bool: true, boolSnack: true, message: "passwords must be at least 6 characters" })
return;
}
firebase.firestore()
.collection('users')
.where('username', '==', username)
.get()
.then((snapshot) => {
if (!snapshot.exist) {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(() => {
if (snapshot.exist) {
return
}
firebase.firestore().collection("users")
.doc(firebase.auth().currentUser.uid)
.set({
name,
email,
username,
image: 'default',
followingCount: 0,
followersCount: 0,
})
})
.catch(() => {
setIsValid({ bool: true, boolSnack: true, message: "Something went wrong" })
})
}
}).catch(() => {
setIsValid({ bool: true, boolSnack: true, message: "Something went wrong" })
})
}
return (
<View style={container.center}>
<View style={container.formCenter}>
<TextInput
style={form.textInput}
placeholder="Username"
value={username}
keyboardType="twitter"
onChangeText={(username) => setUsername(username.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/\s+/g, '').replace(/[^a-z0-9]/gi, ''))}
/>
<TextInput
style={form.textInput}
placeholder="name"
onChangeText={(name) => setName(name)}
/>
<TextInput
style={form.textInput}
placeholder="email"
onChangeText={(email) => setEmail(email)}
/>
<TextInput
style={form.textInput}
placeholder="password"
secureTextEntry={true}
onChangeText={(password) => setPassword(password)}
/>
<Button
style={form.button}
onPress={() => onRegister()}
title="Register"
/>
</View>
<View style={form.bottomButton} >
<Text
onPress={() => props.navigation.navigate("Login")} >
Already have an account? SignIn.
</Text>
</View>
<Snackbar
visible={isValid.boolSnack}
duration={2000}
onDismiss={() => { setIsValid({ boolSnack: false }) }}>
{isValid.message}
</Snackbar>
</View>
)
}
Example #8
Source File: Save.js From InstagramClone with Apache License 2.0 | 4 votes |
function Save(props) {
const [caption, setCaption] = useState("")
const [uploading, setUploading] = useState(false)
const [error, setError] = useState(false)
const [data, setData] = useState("")
const [keyword, setKeyword] = useState("")
useLayoutEffect(() => {
props.navigation.setOptions({
headerRight: () => (
<Feather style={navbar.image} name="check" size={24} color="green" onPress={() => { uploadImage() }} />
),
});
}, [caption]);
const uploadImage = async () => {
if (uploading) {
return;
}
setUploading(true)
let downloadURLStill = null
let downloadURL = await SaveStorage(props.route.params.source, `post/${firebase.auth().currentUser.uid}/${Math.random().toString(36)}`)
if (props.route.params.imageSource != null) {
downloadURLStill = await SaveStorage(props.route.params.imageSource, `post/${firebase.auth().currentUser.uid}/${Math.random().toString(36)}`)
}
savePostData(downloadURL, downloadURLStill);
}
const SaveStorage = async (image, path) => {
if (image == 'default') {
return '';
}
const fileRef = firebase.storage().ref()
.child(path);
const response = await fetch(image);
const blob = await response.blob();
const task = await fileRef.put(blob);
const downloadURL = await task.ref.getDownloadURL();
return downloadURL;
}
const savePostData = (downloadURL, downloadURLStill) => {
let object = {
downloadURL,
caption,
likesCount: 0,
commentsCount: 0,
type: props.route.params.type,
creation: firebase.firestore.FieldValue.serverTimestamp()
}
if (downloadURLStill != null) {
object.downloadURLStill = downloadURLStill
}
firebase.firestore()
.collection('posts')
.doc(firebase.auth().currentUser.uid)
.collection("userPosts")
.add(object).then((result) => {
props.fetchUserPosts()
props.navigation.popToTop()
}).catch((error) => {
setUploading(false)
setError(true)
})
var pattern = /\B@[a-z0-9_-]+/gi;
let array = caption.match(pattern);
if (array !== null) {
for (let i = 0; i < array.length; i++) {
firebase.firestore()
.collection("users")
.where("username", "==", array[i].substring(1))
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
props.sendNotification(doc.data().notificationToken, "New tag", `${props.currentUser.name} Tagged you in a post`, { type: 0, user: firebase.auth().currentUser.uid })
});
})
}
}
}
const renderSuggestionsRow = ({ item }, hidePanel) => {
return (
<TouchableOpacity onPress={() => onSuggestionTap(item.username, hidePanel)}>
<View style={styles.suggestionsRowContainer}>
<View style={styles.userIconBox}>
<Image
style={{ aspectRatio: 1 / 1, height: 45 }}
source={{
uri: item.image
}}
/>
</View>
<View style={styles.userDetailsBox}>
<Text style={styles.displayNameText}>{item.name}</Text>
<Text style={styles.usernameText}>@{item.username}</Text>
</View>
</View>
</TouchableOpacity>
)
}
const onSuggestionTap = (username, hidePanel) => {
hidePanel();
const comment = caption.slice(0, - keyword.length)
setCaption(comment + '@' + username + " ");
}
const callback = (keyword) => {
setKeyword(keyword)
firebase.firestore()
.collection("users")
.where("username", ">=", keyword.substring(1))
.limit(10)
.get()
.then((snapshot) => {
let result = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data }
});
setData(result)
})
}
return (
<View style={[container.container, utils.backgroundWhite]}>
{uploading ? (
<View style={[container.container, utils.justifyCenter, utils.alignItemsCenter]}>
<ActivityIndicator style={utils.marginBottom} size="large" />
<Text style={[text.bold, text.large]}>Upload in progress...</Text>
</View>
) : (
<View style={[container.container]}>
<View style={[container.container, utils.backgroundWhite, utils.padding15]}>
<View style={[{ marginBottom: 20, width: '100%' }]}>
<MentionsTextInput
textInputStyle={{ borderColor: '#ebebeb', borderWidth: 1, padding: 5, fontSize: 15, width: '100%' }}
suggestionsPanelStyle={{ backgroundColor: 'rgba(100,100,100,0.1)' }}
loadingComponent={() => <View style={{ flex: 1, width: 200, justifyContent: 'center', alignItems: 'center' }}><ActivityIndicator /></View>}
textInputMinHeight={30}
textInputMaxHeight={80}
trigger={'@'}
triggerLocation={'new-word-only'} // 'new-word-only', 'anywhere'
value={caption}
onChangeText={setCaption}
triggerCallback={callback.bind(this)}
renderSuggestionsRow={renderSuggestionsRow.bind(this)}
suggestionsData={data}
keyExtractor={(item, index) => item.username}
suggestionRowHeight={45}
horizontal={true}
MaxVisibleRowCount={3}
/>
</View>
<View>
{props.route.params.type ?
<Image
style={container.image}
source={{ uri: props.route.params.source }}
style={{ aspectRatio: 1 / 1, backgroundColor: 'black' }}
/>
:
<Video
source={{ uri: props.route.params.source }}
shouldPlay={true}
isLooping={true}
resizeMode="cover"
style={{ aspectRatio: 1 / 1, backgroundColor: 'black' }}
/>
}
</View>
</View>
<Snackbar
visible={error}
duration={2000}
onDismiss={() => setError(false)}>
Something Went Wrong!
</Snackbar>
</View>
)}
</View>
)
}
Example #9
Source File: Feed.js From InstagramClone with Apache License 2.0 | 4 votes |
function Feed(props) {
const [posts, setPosts] = useState([]);
const [refreshing, setRefreshing] = useState(false)
const [unmutted, setUnmutted] = useState(null)
const [inViewPort, setInViewPort] = useState(0)
const [sheetRef, setSheetRef] = useState(useRef(null))
const [modalShow, setModalShow] = useState({ visible: false, item: null })
const [isValid, setIsValid] = useState(true);
useEffect(() => {
if (props.usersFollowingLoaded == props.following.length && props.following.length !== 0) {
props.feed.sort(function (x, y) {
return y.creation.toDate() - x.creation.toDate();
})
setPosts(props.feed);
setRefreshing(false)
for (let i = 0; i < props.feed.length; i++) {
if (props.feed[i].type == 0) {
setUnmutted(i)
return;
}
}
}
props.navigation.setParams({ param: "value" })
}, [props.usersFollowingLoaded, props.feed])
const onViewableItemsChanged = useRef(({ viewableItems, changed }) => {
if (changed && changed.length > 0) {
setInViewPort(changed[0].index);
}
})
if (posts.length == 0) {
return (<View />)
}
if (sheetRef.current !== null) {
if (modalShow.visible) {
sheetRef.snapTo(0)
} else {
sheetRef.snapTo(1)
}
}
return (
<View style={[container.container, utils.backgroundWhite]}>
<FlatList
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={() => {
setRefreshing(true);
props.reload()
}}
/>
}
onViewableItemsChanged={onViewableItemsChanged.current}
viewabilityConfig={{
waitForInteraction: false,
viewAreaCoveragePercentThreshold: 70
}}
numColumns={1}
horizontal={false}
data={posts}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => (
<View key={index}>
<Post route={{ params: { user: item.user, item, index, unmutted, inViewPort, setUnmuttedMain: setUnmutted, setModalShow, feed: true } }} navigation={props.navigation} />
</View>
)}
/>
<BottomSheet
bottomSheerColor="#FFFFFF"
ref={setSheetRef}
initialPosition={0} //200, 300
snapPoints={[300, 0]}
isBackDrop={true}
isBackDropDismissByPress={true}
isRoundBorderWithTipHeader={true}
backDropColor="black"
isModal
containerStyle={{ backgroundColor: "white" }}
tipStyle={{ backgroundColor: "white" }}
headerStyle={{ backgroundColor: "white", flex: 1 }}
bodyStyle={{ backgroundColor: "white", flex: 1, borderRadius: 20 }}
body={
<View>
{modalShow.item != null ?
<View>
<TouchableOpacity style={{ padding: 20 }}
onPress={() => {
props.navigation.navigate("ProfileOther", { uid: modalShow.item.user.uid, username: undefined });
setModalShow({ visible: false, item: null });
}}>
<Text >Profile</Text>
</TouchableOpacity>
<Divider />
{modalShow.item.creator == firebase.auth().currentUser.uid ?
<TouchableOpacity style={{ padding: 20 }}
onPress={() => {
props.deletePost(modalShow.item).then(() => {
setRefreshing(true);
props.reload()
})
setModalShow({ visible: false, item: null });
}}>
<Text >Delete</Text>
</TouchableOpacity>
: null}
<Divider />
<TouchableOpacity style={{ padding: 20 }} onPress={() => setModalShow({ visible: false, item: null })}>
<Text >Cancel</Text>
</TouchableOpacity>
</View>
: null}
</View>
}
/>
<Snackbar
visible={isValid.boolSnack}
duration={2000}
onDismiss={() => { setIsValid({ boolSnack: false }) }}>
{isValid.message}
</Snackbar>
</View>
)
}
Example #10
Source File: Post.js From InstagramClone with Apache License 2.0 | 4 votes |
function Post(props) {
const [item, setItem] = useState(props.route.params.item)
const [user, setUser] = useState(props.route.params.user)
const [currentUserLike, setCurrentUserLike] = useState(false)
const [unmutted, setUnmutted] = useState(true)
const [videoref, setvideoref] = useState(null)
const [sheetRef, setSheetRef] = useState(useRef(null))
const [modalShow, setModalShow] = useState({ visible: false, item: null })
const [isValid, setIsValid] = useState(true);
const [exists, setExists] = useState(false);
const [loaded, setLoaded] = useState(false);
const isFocused = useIsFocused();
useEffect(() => {
if (props.route.params.notification != undefined) {
firebase.firestore()
.collection("users")
.doc(props.route.params.user)
.get()
.then((snapshot) => {
if (snapshot.exists) {
let user = snapshot.data();
user.uid = snapshot.id;
setUser(user)
}
})
firebase.firestore()
.collection("posts")
.doc(props.route.params.user)
.collection("userPosts")
.doc(props.route.params.item)
.get()
.then((snapshot) => {
if (snapshot.exists) {
let post = snapshot.data();
post.id = snapshot.id;
setItem(post)
setLoaded(true)
setExists(true)
}
})
firebase.firestore()
.collection("posts")
.doc(props.route.params.user)
.collection("userPosts")
.doc(props.route.params.item)
.collection("likes")
.doc(firebase.auth().currentUser.uid)
.onSnapshot((snapshot) => {
let currentUserLike = false;
if (snapshot.exists) {
currentUserLike = true;
}
setCurrentUserLike(currentUserLike)
})
}
else {
firebase.firestore()
.collection("posts")
.doc(props.route.params.user.uid)
.collection("userPosts")
.doc(props.route.params.item.id)
.collection("likes")
.doc(firebase.auth().currentUser.uid)
.onSnapshot((snapshot) => {
let currentUserLike = false;
if (snapshot.exists) {
currentUserLike = true;
}
setCurrentUserLike(currentUserLike)
})
setItem(props.route.params.item)
setUser(props.route.params.user)
setLoaded(true)
setExists(true)
}
}, [props.route.params.notification, props.route.params.item])
useEffect(() => {
if (videoref !== null) {
videoref.setIsMutedAsync(props.route.params.unmutted)
}
setUnmutted(props.route.params.unmutted)
}, [props.route.params.unmutted])
useEffect(() => {
if (videoref !== null) {
if (isFocused) {
videoref.playAsync()
} else {
videoref.stopAsync()
}
}
}, [props.route.params.index, props.route.params.inViewPort])
const onUsernamePress = (username, matchIndex) => {
props.navigation.navigate("ProfileOther", { username, uid: undefined })
}
const onLikePress = (userId, postId, item) => {
item.likesCount += 1;
setCurrentUserLike(true)
firebase.firestore()
.collection("posts")
.doc(userId)
.collection("userPosts")
.doc(postId)
.collection("likes")
.doc(firebase.auth().currentUser.uid)
.set({})
.then()
props.sendNotification(user.notificationToken, "New Like", `${props.currentUser.name} liked your post`, { type: 0, postId, user: firebase.auth().currentUser.uid })
}
const onDislikePress = (userId, postId, item) => {
item.likesCount -= 1;
setCurrentUserLike(false)
firebase.firestore()
.collection("posts")
.doc(userId)
.collection("userPosts")
.doc(postId)
.collection("likes")
.doc(firebase.auth().currentUser.uid)
.delete()
}
if (!exists && loaded) {
return (
<View style={{ height: '100%', justifyContent: 'center', margin: 'auto' }}>
<FontAwesome5 style={{ alignSelf: 'center', marginBottom: 20 }} name="dizzy" size={40} color="black" />
<Text style={[text.notAvailable]}>Post does not exist</Text>
</View>
)
}
if (!loaded) {
return (<View></View>)
}
if (user == undefined) {
return (<View></View>)
}
if (item == null) {
return (<View />)
}
const _handleVideoRef = (component) => {
setvideoref(component);
if (component !== null) {
component.setIsMutedAsync(props.route.params.unmutted)
}
}
if (videoref !== null) {
videoref.setIsMutedAsync(unmutted)
if (isFocused && props.route.params.index == props.route.params.inViewPort) {
videoref.playAsync()
} else {
videoref.stopAsync()
}
}
if (sheetRef.current !== null && !props.route.params.feed) {
if (modalShow.visible) {
sheetRef.snapTo(0)
} else {
sheetRef.snapTo(1)
}
}
return (
<View style={[container.container, utils.backgroundWhite]}>
<View>
<View style={[container.horizontal, { alignItems: 'center', padding: 10 }]}>
<TouchableOpacity
style={[container.horizontal, { alignItems: 'center' }]}
onPress={() => props.navigation.navigate("ProfileOther", { uid: user.uid, username: undefined })}>
{user.image == 'default' ?
(
<FontAwesome5
style={[utils.profileImageSmall]}
name="user-circle" size={35} color="black" />
)
:
(
<Image
style={[utils.profileImageSmall]}
source={{
uri: user.image
}}
/>
)
}
<View style={{ alignSelf: 'center' }}>
<Text style={[text.bold, text.medium, { marginBottom: 0 }]} >{user.name}</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
style={[{ marginLeft: 'auto' }]}
onPress={() => {
if (props.route.params.feed) {
props.route.params.setModalShow({ visible: true, item })
} else {
setModalShow({ visible: true, item })
}
}}>
<Feather
name="more-vertical" size={20} color="black" />
</TouchableOpacity>
</View>
{item.type == 0 ?
<View>
{props.route.params.index == props.route.params.inViewPort && isFocused ?
<View>
<VideoPlayer
videoProps={{
isLooping: true,
shouldPlay: true,
resizeMode: Video.RESIZE_MODE_COVER,
source: {
uri: item.downloadURL,
},
videoRef: _handleVideoRef,
}}
inFullscreen={false}
showControlsOnLoad={true}
showFullscreenButton={false}
height={WINDOW_WIDTH}
width={WINDOW_WIDTH}
shouldPlay={true}
isLooping={true}
style={{
aspectRatio: 1 / 1, height: WINDOW_WIDTH,
width: WINDOW_WIDTH, backgroundColor: 'black'
}}
/>
<TouchableOpacity
style={{ position: 'absolute', borderRadius: 500, backgroundColor: 'black', width: 40, height: 40, alignItems: 'center', justifyContent: 'center', margin: 10, right: 0 }}
activeOpacity={1}
onPress={() => {
if (videoref == null) {
return;
}
if (unmutted) {
if (props.route.params.setUnmuttedMain == undefined) {
setUnmutted(false)
} else {
props.route.params.setUnmuttedMain(false)
}
} else {
if (props.route.params.setUnmuttedMain == undefined) {
setUnmutted(true)
} else {
props.route.params.setUnmuttedMain(true)
}
}
}}>
{!unmutted ?
<Feather name="volume-2" size={20} color="white" />
:
<Feather name="volume-x" size={20} color="white" />
}
</TouchableOpacity>
</View>
:
<View style={{ marginTop: 4 }}>
<CachedImage
cacheKey={item.id}
style={[container.image]}
source={{ uri: item.downloadURLStill }}
/>
</View>
}
</View>
:
<CachedImage
cacheKey={item.id}
style={container.image}
source={{ uri: item.downloadURL }}
/>
}
<View style={[utils.padding10, container.horizontal]}>
{currentUserLike ?
(
<Entypo name="heart" size={30} color="red" onPress={() => onDislikePress(user.uid, item.id, item)} />
)
:
(
<Feather name="heart" size={30} color="black" onPress={() => onLikePress(user.uid, item.id, item)} />
)
}
<Feather style={utils.margin15Left} name="message-square" size={30} color="black" onPress={() => props.navigation.navigate('Comment', { postId: item.id, uid: user.uid, user })} />
<Feather style={utils.margin15Left} name="share" size={26} color="black" onPress={() => props.navigation.navigate('ChatList', { postId: item.id, post: { ...item, user: user }, share: true })} />
</View>
<View style={[container.container, utils.padding10Sides]}>
<Text style={[text.bold, text.medium]}>
{item.likesCount} likes
</Text>
<Text style={[utils.margin15Right, utils.margin5Bottom]}>
<Text style={[text.bold]}
onPress={() => props.navigation.navigate("ProfileOther", { uid: user.uid, username: undefined })}>
{user.name}
</Text>
<Text> </Text>
<ParsedText
parse={
[
{ pattern: /@(\w+)/, style: { color: 'green', fontWeight: 'bold' }, onPress: onUsernamePress },
]
}
>{item.caption}</ParsedText>
</Text>
<Text
style={[text.grey, utils.margin5Bottom]} onPress={() => props.navigation.navigate('Comment', { postId: item.id, uid: user.uid, user })}>
View all {item.commentsCount} Comments
</Text>
<Text
style={[text.grey, text.small, utils.margin5Bottom]}>
{timeDifference(new Date(), item.creation.toDate())}
</Text>
</View>
</View>
<BottomSheet
bottomSheerColor="#FFFFFF"
ref={setSheetRef}
initialPosition={0} //200, 300
snapPoints={[300, 0]}
isBackDrop={true}
isBackDropDismissByPress={true}
isRoundBorderWithTipHeader={true}
backDropColor="black"
isModal
containerStyle={{ backgroundColor: "white" }}
tipStyle={{ backgroundColor: "white" }}
headerStyle={{ backgroundColor: "white", flex: 1 }}
bodyStyle={{ backgroundColor: "white", flex: 1, borderRadius: 20 }}
body={
<View>
{modalShow.item != null ?
<View>
<TouchableOpacity style={{ padding: 20 }}
onPress={() => {
props.navigation.navigate("ProfileOther", { uid: modalShow.item.user.uid, username: undefined });
setModalShow({ visible: false, item: null });
}}>
<Text >Profile</Text>
</TouchableOpacity>
<Divider />
{props.route.params.user.uid == firebase.auth().currentUser.uid ?
<TouchableOpacity style={{ padding: 20 }}
onPress={() => {
props.deletePost(modalShow.item).then(() => {
props.fetchUserPosts()
props.navigation.popToTop()
})
setModalShow({ visible: false, item: null });
}}>
<Text >Delete</Text>
</TouchableOpacity>
: null}
<Divider />
<TouchableOpacity style={{ padding: 20 }} onPress={() => setModalShow({ visible: false, item: null })}>
<Text >Cancel</Text>
</TouchableOpacity>
</View>
: null}
</View>
}
/>
<Snackbar
visible={isValid.boolSnack}
duration={2000}
onDismiss={() => { setIsValid({ boolSnack: false }) }}>
{isValid.message}
</Snackbar>
</View>
)
}
Example #11
Source File: index.js From spree-react-native with MIT License | 4 votes |
BagScreen = ({ navigation, dispatch, saving, cart }) => {
const [promoCode, setPromoCode] = React.useState('')
const [snackbarVisible, setSnackbarVisible] = React.useState(false)
React.useEffect(() => {
dispatch(getCart())
}, [])
const handleToCheckout = async () => {
if(cart.state === "cart") {
await dispatch(getDefaultCountry())
await dispatch(getCountriesList())
navigation.navigate('ShippingAddress')
} else {
navigation.navigate('CheckoutPayment')
}
}
const handleRemoveLineItem = (lineItemId) => {
dispatch(removeLineItem(lineItemId))
}
const handleIncrementQuantity = (lineItemId, lineItemQuantity) => {
dispatch(setQuantity(
{
line_item_id: lineItemId,
quantity: lineItemQuantity + 1
}
))
}
const handleDecrementQuantity = (lineItemId, lineItemQuantity) => {
if(lineItemQuantity === 1) {
handleRemoveLineItem(lineItemId)
} else {
dispatch(setQuantity(
{
line_item_id: lineItemId,
quantity: lineItemQuantity - 1
}
))
}
}
if(saving) {
return (
<ActivityIndicatorCard />
)
} else
return (
<>
<View style={ globalStyles.containerFluid }>
<ScrollView>
<View style={globalStyles.container}>
{
cart.line_items.map((ele, i) => <ProductCard
key={i}
cart
counter
imageSource={ele.variant.images[0].styles[3].url}
onIncrementQuantity={() => handleIncrementQuantity(ele.id, ele.quantity)}
onDecrementQuantity={() => handleDecrementQuantity(ele.id, ele.quantity)}
onRemoveLineItem={() => handleRemoveLineItem(ele.id)}
{...ele}
/>)
}
</View>
<View style={[globalStyles.containerFluid, globalStyles.bgWhite, globalStyles.mt16]}>
<View style={[ globalStyles.container, globalStyles.mt8 ]}>
<Text style={[ globalStyles.latoBold14, globalStyles.mb8 ]}>Promo Code</Text>
<TextField
placeholder=" Enter Promo Code"
containerStyle={checkoutStyles.inputWrapperStyle}
rightElement={<Text style={checkoutStyles.inputRightText}>Apply</Text>}
onChangeText={setPromoCode}
value={promoCode}
/>
</View>
</View>
<CheckoutDetailsCard title="Price Details" display_total={cart && cart.display_total} />
<View style={styles.footer}>
<Text style={[globalStyles.textPrimary, globalStyles.latoBold16]}>Continue Shopping</Text>
</View>
</ScrollView>
<ActionButtonFooter
title="Proceed to Checkout"
onPress={handleToCheckout}
/>
</View>
<Snackbar
visible={snackbarVisible}
duration={3000}
>
SetQuantity Success !
</Snackbar>
</>
)
}
Example #12
Source File: index.js From spree-react-native with MIT License | 4 votes |
ProductDetailScreen = ({ dispatch, product, auth, saving }) => {
const [pincode, setPincode] = useState('')
const [isVariantSelected, setIsVariantSelected] = useState(true)
const [activeColor, setActiveColor] = useState(product.default_variant.option_values[0].presentation)
const [activeSize, setActiveSize] = useState('')
const [selectedVariant, setSelectedVariant] = useState({})
const [imageURI, setImageURI] = useState(`${HOST}/${product.variants[0].images[0].styles[3].url}`)
const [snackbarVisible, setSnackbarVisible] = useState(false)
const [variantDistinctColors] = useState([...new Set(product.variants.map(variant => variant.option_values[0].presentation))])
const handleColorSelection = ({index, color}) => {
setActiveColor(color)
setActiveSize('')
setSelectedVariant({})
setIsVariantSelected(true)
setImageURI(`${HOST}/${product.variants[index].images[0].styles[3].url}`)
}
const handleAddToBag = () => {
dispatch(addItem(
{
variant_id: selectedVariant.id,
quantity: 1,
}
))
// setSnackbarVisible(true)
}
if(saving) {
return (
<ActivityIndicatorCard />
)
} else
return (
<>
<ScrollView style={globalStyles.containerFluid}>
<MyCarousel key={imageURI} imageURI={imageURI} />
<View style={ styles.containerFluid }>
<View style={[ globalStyles.container, globalStyles.pb16 ]}>
<Text style={ globalStyles.latoBold18 }>{ product.name }</Text>
<Text style={ styles.description }>{ product.description }</Text>
<View style={[ styles.pricingContainer, globalStyles.mt8 ]}>
<Text style={ styles.discountedPrice }>{ product.display_price }</Text>
<Text style={ styles.price }>$32.90</Text>
<Text style={ styles.discountPercent }>(20% OFF)</Text>
<Text style={[ globalStyles.latoBold14, globalStyles.textSuccess ]}>Inclusive of all taxes</Text>
</View>
</View>
</View>
<View style={[ styles.containerFluid, globalStyles.mt16 ]}>
<View style={[ globalStyles.container, globalStyles.pv8 ]}>
<Text style={ globalStyles.latoBold14 }>You get it for
<Text style={[ globalStyles.prices, globalStyles.textPrimary ]}> $25.49</Text>
<Text style={[ globalStyles.prices, globalStyles.textSuccess ]}> (Save $4.50)</Text>
</Text>
</View>
</View>
<View style={[ styles.containerFluid, globalStyles.mt8 ]}>
<View style={[ globalStyles.container, globalStyles.pv8 ]}>
<View style={styles.rowContainer}>
<Button
title="Save For Later"
type="outline"
disabled={isVariantSelected}
disabledStyle={{ borderColor: colors.gray, color: colors.gray }}
containerStyle={{ flex: 1, marginRight: 16 }}
buttonStyle={globalStyles.btn}
titleStyle={styles.titleStyle}
onPress={() => dispatch(setProductFavourite(selectedVariant))}
/>
<Button
title="Add To Bag"
type="solid"
disabled={isVariantSelected}
disabledStyle={{ backgroundColor: colors.gray }}
disabledTitleStyle={{ color: colors.white }}
containerStyle={{flex: 1}}
buttonStyle={[ globalStyles.btn, globalStyles.btnSolid ]}
onPress={handleAddToBag}
/>
</View>
<View style={ globalStyles.mt16 }>
<Text style={ globalStyles.latoBold14 }>Select Color</Text>
<ScrollView horizontal={true} style={[ styles.rowContainer, globalStyles.mt8 ]}>
{
variantDistinctColors.map((color, index) => (
<Avatar
key={index}
size="small"
rounded
onPress={() => handleColorSelection(
{
index: index,
color: color
}
)}
containerStyle={{
backgroundColor: `${color}`,
marginRight: 16,
borderWidth: 1,
padding: 1,
borderColor: color !== activeColor ? colors.gray : colors.primary
}}
/>
))
}
</ScrollView>
</View>
<View>
{activeColor ? <View style={[ styles.sizingTitleContainer, globalStyles.mt16 ]}>
<Text style={[ globalStyles.latoBold14, globalStyles.textDark ]}>Select Size</Text>
<Text style={[ globalStyles.latoBold14, globalStyles.textPrimary ]}>Size Help?</Text>
</View> : null }
<View style={[ styles.rowContainer, globalStyles.mt8 ]}>
{
product.variants.map((variant, index) => {
if(variant.option_values[0].presentation === activeColor) {
return <Avatar
key={index}
size="small"
title={`${variant.option_values[1].presentation}`}
onPress={() => {
setActiveSize(variant.option_values[1].presentation)
setSelectedVariant(variant)
setIsVariantSelected(false)
}
}
rounded
activeOpacity={0.7}
containerStyle={{
backgroundColor: colors.white,
marginRight: 16,
borderColor: variant.option_values[1].presentation !== activeSize ? colors.black : colors.primary,
borderWidth: 1
}}
titleStyle={[globalStyles.latoBold14,
variant.option_values[1].presentation !== activeSize ? globalStyles.textDark : globalStyles.textPrimary
]}
/>
} else { return null }
})
}
</View>
</View>
</View>
</View>
<View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv8 ]}>
<View style={ globalStyles.container }>
<View>
<Text style={ globalStyles.latoBold14 }>Product Detail & Care</Text>
<View style={[ styles.unorderedListItem, globalStyles.mt8 ]}>
{
product.product_properties.map(property => (
<Text key={property.id} style={globalStyles.label}>
{'\u2022'} {capitalizeFirstLetter(property.name)}: {property.value}
</Text>
))
}
</View>
</View>
<View style={ globalStyles.mt16 }>
<Text style={ globalStyles.latoBold14 }>Description</Text>
<Text style={[ globalStyles.label, globalStyles.mt8 ]}>
{ product.description }
</Text>
</View>
<View style={ globalStyles.mt16 }>
<Text style={ globalStyles.latoBold14 }>Manufacturer</Text>
<Text style={[ globalStyles.label, globalStyles.mt8 ]}>Freeway Clothing Co, 768/1, Vijaynagar, New Delhi 116708</Text>
</View>
<View style={ globalStyles.mt16 }>
<Text style={ globalStyles.latoBold14 }>Manufacturer Country</Text>
<Text style={[ globalStyles.label, globalStyles.mt8 ]}>India</Text>
</View>
</View>
</View>
<View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv8 ]}>
<View style={ globalStyles.container }>
<Text style={ globalStyles.latoBold14 }>Customer Reviews (309)</Text>
{
[{
id: 0,
review: 'Purchasing the dress online was super easy and they were delivered quick. My partner absolutely loves his new dress! Perfect! All she had to do was swap them over with his old party dress.',
reviewer: 'Devendar Rathore',
date: 'Aug 19, 2020',
likes: 16,
dislikes: 7
},
{
id: 1,
review: 'My old dress was become dull and stale. But this new dress is super amazing and fits nicely to me. Thanks for super quick delivery and good service.',
reviewer: 'Devendar Rathore',
date: 'Aug 19, 2020',
likes: 46,
dislikes: 6
}].map((item, i, arr) => (
<View key={item.id} style={ globalStyles.pv8 }>
<Text style={globalStyles.latoRegular}>{ item.review }</Text>
<View style={styles.reviewFooter}>
<Text style={globalStyles.label}>{ item.reviewer } | { item.date }</Text>
<View style={styles.likesDislikesContainer}>
<View style={styles.likesContainer}>
<Smile size={20} style={{color: colors.gray}}/>
<Text style={globalStyles.label}> { item.likes }</Text>
</View>
<View style={styles.likesContainer}>
<SmileSad size={20} style={{color: colors.gray}}/>
<Text style={globalStyles.label}> { item.dislikes }</Text>
</View>
</View>
</View>
{ i !== arr.length - 1 && <Divider style={styles.reviewBorder} /> }
</View>
))
}
<TouchableOpacity>
<Text style={styles.reviewFooterAction}>View All (309)</Text>
</TouchableOpacity>
</View>
</View>
<View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv8 ]}>
<View style={ globalStyles.container }>
<Text style={[ globalStyles.latoBold14, globalStyles.mb8 ]}>Check Delivery</Text>
<TextField
placeholder=" Enter PIN Code"
containerStyle={styles.inputWrapperStyle}
rightElement={<Text style={styles.inputRight}>Check</Text>}
onChangeText={setPincode}
value={pincode}
/>
<View style={ styles.deliveryOffersContainer }>
<ShoppingCart size={18} style={[styles.deliveryOffersIcon, {transform: [{ rotateY: '180deg' }]} ]}/>
<Text style={ globalStyles.latoBold14 }>Delivery by Thursday, Sep 05</Text>
</View>
<View style={ styles.deliveryOffersContainer }>
<Dollar size={18} style={ styles.deliveryOffersIcon }/>
<Text style={ globalStyles.latoBold14 }>Cash on delivery available</Text>
</View>
<View style={ styles.deliveryOffersContainer }>
<Repeat size={18} style={ styles.deliveryOffersIcon }/>
<Text style={ globalStyles.latoBold14 }>Return & exchange available within 10 days</Text>
</View>
</View>
</View>
<View style={[ styles.containerFluid, globalStyles.mt8, globalStyles.pv16 ]}>
<View style={globalStyles.container}>
<View style={styles.alikeProductsHeader}>
<Text style={[ globalStyles.latoBold14, globalStyles.mb16 ]}>Your might also like</Text>
<Text style={[ globalStyles.label, globalStyles.latoBold14 ]}>12 more</Text>
</View>
</View>
<ScrollView horizontal={true} style={styles.carouselProductsContainer}>
<CarouselProductCard imageURI={imageURI} />
<CarouselProductCard imageURI={imageURI} />
<CarouselProductCard imageURI={imageURI} />
</ScrollView>
</View>
<View style={styles.footerContainer}>
<View style={styles.footerItemListContainer}>
<View style={styles.footerItemContainer}>
<CustomIconTruck size={32} style={styles.footerIcon} />
<Text style={styles.footerText}>Fastest Delivery</Text>
</View>
<View style={styles.footerItemContainer}>
<CustomIconOriginal size={32} style={styles.footerIcon} />
<Text style={styles.footerText}>100% Original</Text>
</View>
<View style={styles.footerItemContainer}>
<IcOutlineAssignmentReturn size={32} style={styles.footerIcon} />
<Text style={styles.footerText}>Easy Returns</Text>
</View>
<View style={styles.footerItemContainer}>
<RiSecurePaymentFill size={32} style={styles.footerIcon} />
<Text style={styles.footerText}>Secure Payment</Text>
</View>
</View>
</View>
</ScrollView>
<Snackbar
visible={snackbarVisible}
duration={2000}
>
Added to Bag !
</Snackbar>
</>
)
}
Example #13
Source File: RequestTokenForm.js From mern-stack with MIT License | 4 votes |
render() {
const {
clearErrorMessage,
errorMessage,
isProcessing,
navigation,
title,
theme: { colors },
} = this.props;
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : null}
style={styles.container}
>
<ScrollView
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<IconButton
icon="chevron-left"
color={colors.primary}
size={30}
accessibilityLabel="Back to sign in"
onPress={() => navigation.goBack()}
/>
<Logo />
<Spacer>
<Title style={{ alignSelf: 'center', color: colors.primary }}>
{title}
</Title>
</Spacer>
<Spacer>
<TextInput
label="Email"
mode="outlined"
dense
value={this.state.email}
autoCapitalize="none"
autoCorrect={false}
keyboardType="email-address"
onChangeText={(email) => this.setState({ email })}
onSubmitEditing={this.onSubmit}
onFocus={clearErrorMessage}
disabled={isProcessing || !!this.state.message}
/>
</Spacer>
<Spacer vertical={16}>
<Button
mode="contained"
accessibilityLabel="Submit"
onPress={this.onSubmit}
loading={isProcessing}
disabled={isProcessing || !!this.state.message}
>
Submit
</Button>
</Spacer>
</ScrollView>
<Snackbar
visible={errorMessage}
onDismiss={clearErrorMessage}
action={{
label: 'Dismiss',
accessibilityLabel: 'Dismiss',
onPress: () => {},
}}
>
{errorMessage}
</Snackbar>
<Snackbar
visible={this.state.message}
onDismiss={() => navigation.goBack()}
action={{
label: 'Go Back',
accessibilityLabel: 'Go Back',
onPress: () => {},
}}
>
{this.state.message}
</Snackbar>
</KeyboardAvoidingView>
);
}
Example #14
Source File: SignInScreen.js From mern-stack with MIT License | 4 votes |
render() {
const {
clearErrorMessage,
errorMessage,
isProcessing,
theme: { colors },
type,
unloadAuthScreen,
} = this.props;
return (
<SafeAreaView forceInset={{ top: 'always' }} style={styles.container}>
<NavigationEvents onWillBlur={unloadAuthScreen} />
<StatusBar barStyle="dark-content" />
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : null}
style={styles.container}
>
<ScrollView
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<Logo />
<Spacer>
<Title style={{ alignSelf: 'center', color: colors.primary }}>
Sign In
</Title>
</Spacer>
<Spacer>
<TextInput
label="Email"
mode="outlined"
dense
value={this.state.email}
autoCapitalize="none"
autoCorrect={false}
keyboardType="email-address"
onChangeText={(email) => this.setState({ email })}
onSubmitEditing={this.onEmailSignIn}
onFocus={clearErrorMessage}
disabled={isProcessing}
/>
<Spacer />
<TextInput
label="Password"
mode="outlined"
dense
secureTextEntry
value={this.state.password}
autoCapitalize="none"
autoCorrect={false}
onChangeText={(password) => this.setState({ password })}
onSubmitEditing={this.onEmailSignIn}
onFocus={clearErrorMessage}
disabled={isProcessing}
/>
<View style={styles.navLinks}>
<NavLink
text="Forgot password?"
routeName="RequestPasswordReset"
disabled={isProcessing}
/>
<NavLink
text="Register instead!"
routeName="SignUp"
disabled={isProcessing}
/>
</View>
</Spacer>
<Spacer vertical={4}>
<Button
mode="contained"
accessibilityLabel="Sign In"
onPress={this.onEmailSignIn}
loading={isProcessing && type === 'email'}
disabled={isProcessing}
>
Sign In
</Button>
</Spacer>
<Spacer vertical={12}>
<Text style={{ alignSelf: 'center' }}>Or Sign In With</Text>
</Spacer>
<Spacer>
<OAuthButtons />
</Spacer>
{errorMessage === 'Email is not verified' && (
<NavLink
text="Have not received verification email?"
routeName="RequestVerificationEmail"
disabled={isProcessing}
/>
)}
</ScrollView>
<Snackbar
visible={errorMessage}
onDismiss={clearErrorMessage}
action={{
label: 'Dismiss',
accessibilityLabel: 'Dismiss',
onPress: () => {},
}}
>
{errorMessage}
</Snackbar>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
Example #15
Source File: SignUpScreen.js From mern-stack with MIT License | 4 votes |
render() {
const {
clearErrorMessage,
errorMessage,
isProcessing,
theme: { colors },
type,
unloadAuthScreen,
} = this.props;
return (
<SafeAreaView forceInset={{ top: 'always' }} style={styles.container}>
<NavigationEvents onWillBlur={unloadAuthScreen} />
<StatusBar barStyle="dark-content" />
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : null}
style={styles.container}
>
<ScrollView
keyboardShouldPersistTaps="handled"
keyboardDismissMode="on-drag"
>
<Logo />
<Spacer>
<Title style={{ alignSelf: 'center', color: colors.primary }}>
Sign Up
</Title>
</Spacer>
<Spacer>
<TextInput
label="Username"
mode="outlined"
dense
value={this.state.username}
autoCapitalize="none"
autoCorrect={false}
onChangeText={(username) => this.setState({ username })}
onSubmitEditing={this.onEmailRegister}
onFocus={clearErrorMessage}
disabled={isProcessing}
/>
<Spacer />
<TextInput
label="Email"
mode="outlined"
dense
value={this.state.email}
autoCapitalize="none"
autoCorrect={false}
keyboardType="email-address"
onChangeText={(email) => this.setState({ email })}
onSubmitEditing={this.onEmailRegister}
onFocus={clearErrorMessage}
disabled={isProcessing}
/>
<Spacer />
<View style={styles.fullName}>
<TextInput
label="First Name"
mode="outlined"
style={styles.name}
dense
value={this.state.firstName}
autoCorrect={false}
onChangeText={(firstName) => this.setState({ firstName })}
onSubmitEditing={this.onEmailRegister}
onFocus={clearErrorMessage}
disabled={isProcessing}
/>
<TextInput
label="Last Name"
mode="outlined"
style={styles.name}
dense
value={this.state.lastName}
autoCorrect={false}
onChangeText={(lastName) => this.setState({ lastName })}
onSubmitEditing={this.onEmailRegister}
onFocus={clearErrorMessage}
disabled={isProcessing}
/>
</View>
<Spacer />
<TextInput
label="Password"
mode="outlined"
dense
secureTextEntry
value={this.state.password}
autoCapitalize="none"
autoCorrect={false}
onChangeText={(password) => this.setState({ password })}
onSubmitEditing={this.onEmailRegister}
onFocus={clearErrorMessage}
disabled={isProcessing}
/>
<View style={styles.navLinks}>
<NavLink text="Sign in instead!" routeName="SignIn" />
</View>
</Spacer>
<Spacer vertical={4}>
<Button
mode="contained"
accessibilityLabel="Sign In"
onPress={this.onEmailRegister}
loading={isProcessing && type === 'email'}
disabled={isProcessing}
>
Sign Up
</Button>
</Spacer>
<Spacer vertical={12}>
<Text style={{ alignSelf: 'center' }}>Or Sign Up With</Text>
</Spacer>
<Spacer>
<OAuthButtons />
</Spacer>
</ScrollView>
<Snackbar
visible={errorMessage}
onDismiss={clearErrorMessage}
action={{
label: 'Dismiss',
accessibilityLabel: 'Dismiss',
onPress: () => {},
}}
>
{errorMessage}
</Snackbar>
</KeyboardAvoidingView>
</SafeAreaView>
);
}