need clarification about LayoutAnimation - react-native

I've been trying to understand how to use LayoutAnimation and the docs haven't been very helpful.
is there a better source? anyways here is this code which demonstrates the 3 different types of animations with layoutAnimation. It is an app with 3 buttons and 3 boxes which move across the screen differently. I am failing to understand what causes the boxes to animate. I don't see a function call making it animate. I only see conditional statements in the style attribute. the attribute seems to know nothing about the layoutAnimation. Yet it does animate.
here is the code
import React, { useState } from "react";
import {
View,
Platform,
UIManager,
LayoutAnimation,
StyleSheet,
Button
} from "react-native";
if (
Platform.OS === "android" &&
UIManager.setLayoutAnimationEnabledExperimental
) {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
export default function App() {
const [firstBoxPosition, setFirstBoxPosition] = useState("right");
const [secondBoxPosition, setSecondBoxPosition] = useState("left");
const [thirdBoxPosition, setThirdBoxPosition] = useState("left");
const toggleFirstBox = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
setFirstBoxPosition(firstBoxPosition === "left" ? "right" : "left");
};
const toggleSecondBox = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.linear);
setSecondBoxPosition(secondBoxPosition === "left" ? "right" : "left");
};
const toggleThirdBox = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
setThirdBoxPosition(thirdBoxPosition === "left" ? "right" : "left");
};
return (
<View style={styles.container}>
{/* button demonstrating easing animation*/}
<View style={styles.buttonContainer}>
<Button title="EaseInEaseOut" onPress={toggleFirstBox} />
</View>
{/* button demonstrating linear animation*/}
<View style={styles.buttonContainer}>
<Button title="Linear" onPress={toggleSecondBox} />
</View>
{/* button demonstrating spring animation*/}
<View style={styles.buttonContainer}>
<Button title="Spring" onPress={toggleThirdBox} />
</View>
{/*The three boxes demonstrating animation types*/}
<View
style={[
styles.box,
firstBoxPosition === "left" ? null : styles.moveRight
]}
/>
<View
style={[
styles.box,
secondBoxPosition === "left" ? null : styles.moveRight
]}
/>
<View
style={[
styles.box,
thirdBoxPosition === "left" ? null : styles.moveRight
]}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "flex-start",
justifyContent: "center"
},
box: {
height: 100,
width: 100,
borderRadius: 5,
margin: 8,
backgroundColor: "blue"
},
moveRight: {
alignSelf: "flex-end"
},
buttonContainer: {
alignSelf: "center"
}
});

The idea (and the major gotcha) with LayoutAnimation is that it sets an animation for ALL subsequent layout changes until it's removed. It just works automatically with no additional setup.

Related

SafeAreaView does not take the whole screen after placing on the background

I am using RN 0.59. Every time I placed the app on the background then reopen it immediately, the SafeAreaView does not take the whole screen.
But, if I placed the app on the background and reopen it after a while (for about 3 seconds) it is working fine.
Here's my snippet on SafeAreaView
...
const SafeAreaViewUI = ({children}) => {
return (
<SafeAreaView style={styles.container}>
<View style={styles.content}>
{ children }
</View>
</SafeAreaView>
);
};
...
export default SafeAreaViewUI;
for my styling
container: {
flex: 1,
backgroundColor: Platform.OS === 'android' ? blurple : null,
paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0,
},
content: {
flexGrow: 1,
color: text,
backgroundColor: white,
}
Any insight for this one?
This worked on my end.
const SafeAreaViewUI = ({children}) => {
const [ height, setHeight ] = useState(0)
return (
<SafeAreaView
onLayout={() => {
if (Platform.OS === 'android') {
setHeight(StatusBar.currentHeight || 0);
}
}}
style={[styles.container, { paddingTop: height }]}>
<View style={styles.content}>
{ children }
</View>
</SafeAreaView>
);
If there's other possible answer. Kindly post it here.
Thanks!

Build a custom seconds and minutes input in React Native?

Im making an exercise timer and I need an input for seconds and minutes.
The ideal UX would 2 select lists side by side. Tapping on the input would open both lists, so different from the web where you can only focus on one at a time.
Ive made a demo here, although it would need to be in a modal or similar:
https://snack.expo.io/#jamesweblondon/intelligent-apple
import * as React from 'react';
import { Text, View, StyleSheet, ScrollView, TouchableOpacity } from 'react-native';
const minutes = new Array(10).fill('').map((item, index)=>{
return index;
})
const seconds = new Array(60).fill('').map((item, index)=>{
return index;
})
const Item = ({text, isSelected, onPress}) => {
return(
<TouchableOpacity
onPress={onPress}
style={[styles.item, isSelected && styles.itemIsSelected]}>
{text}
</TouchableOpacity>
)
}
export default function App() {
const [selectedMinute, setSelectedMinute] = React.useState(1);
const [selectedSeconds, setSelectedSeconds] = React.useState(10);
return (
<View style={styles.container}>
<View style={styles.row}>
<Text style={styles.heading}>Minutes</Text>
<ScrollView style={styles.scroll}>
{
minutes.map((item, index)=>{
return <Item
onPress={()=>setSelectedMinute(item)}
text={item}
key={item}
isSelected={selectedMinute === index}
/>
})
}
</ScrollView>
</View>
<View style={styles.row}>
<Text style={styles.heading}>Seconds</Text>
<ScrollView style={styles.scroll}>
{
seconds.map((item, index)=>{
return <Item
onPress={()=>setSelectedSeconds(item)}
text={item}
key={item}
isSelected={selectedSeconds === index}
/>
})
}
</ScrollView>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
height: 300
},
row: {
flex: 1,
},
scroll: {
height: 300
},
heading: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center'
},
item: {
padding: 30,
backgroundColor: 'grey',
borderColor: 'white',
borderWidth: 1,
justifyContent: 'center',
alignItems: 'center'
},
itemIsSelected: {
backgroundColor: 'gold'
}
});
Is it OK to build your own inputs in React Native? This would be a a bad idea on the web as it would probably result in worse UX (especially for keyboard navigation) and a component that screen readers wouldn't know how to use.
I couldn't find a library that does quite what I need. This is close but you can only have one list open at a time. It also had a major bug with Redux making it unusable for me:
https://github.com/lawnstarter/react-native-picker-select#readme
Ive been trying to use the Picker component as I imagine it's more semantic? It works how I need on iOS but not Android (see screenshots):

Make autoscroll viewpager in reactnative

I am trying to make the sliding image. I have followed the this . Its responding on sliding with fingers but not sliding automatically. How can I do so? I have implemented as follows:
<ViewPager style={styles.viewPager} initialPage={0}>
<View key="1">
<Image style={ {height: '100%', width:'100%'}}source={{uri :'https://images.unsplash.com/photo-1441742917377-57f78ee0e582?h=1024'}}></Image>
</View>
<View key="2">
<Image style={ {height: '100%', width:'100%'}}source={{uri :'https://images.unsplash.com/photo-1441716844725-09cedc13a4e7?h=1024'}}></Image>
</View>
</ViewPager>
By looking at the source code I have found there is a method setPage() which accepts page number as argument.
Look at the example code they have provided where you can find how to use reference and call setPage method Example
Now you can use setInterval() and make auto slide work.
setInterval(() => {
this.viewPager.current.setPage(page);
}, 1000);
Set page is a method to update the page of the viewpager. You can autoscroll the viewpager using a timer and by updating the pager by using the setPage method. Below is the complete code for the same.
import React, { Component } from 'react';
import { StyleSheet, View, Text, Platform } from 'react-native';
import ViewPager from '#react-native-community/viewpager';
export default class App extends Component {
state = {
pageNumber: 0,
totalPage: 2
}
componentDidMount() {
var pageNumber = 0;
setInterval(() => {
if (this.state.pageNumber >= 2) {
pageNumber = 0;
} else {
pageNumber = this.state.pageNumber;
pageNumber++;
}
console.log(pageNumber)
this.setState({ pageNumber: pageNumber })
this.viewPager.setPage(pageNumber)
}, 2000);
}
render() {
return (
<View style={{ flex: 1 }}>
<ViewPager style={styles.viewPager} initialPage={0}
ref={(viewPager) => { this.viewPager = viewPager }}
scrollEnabled={true}>
<View key="1">
<Text style={{ color: 'black' }}>First page</Text>
</View>
<View key="2">
<Text>Second page</Text>
</View>
<View key="3">
<Text>Third page</Text>
</View>
</ViewPager>
</View>
);
}
}
const styles = StyleSheet.create({
viewPager: {
flex: 1,
},
});

How to stick the comment input box on top of keyboard [duplicate]

So I need to align a button Which is not at bottom om screen by design should be at middle of screen but it should align to be on top of the keyboard for all devices.
If you check this screenshot :
for Some devices I mange to do it, but in some others is not really aligned :
how can I manage this to work in all?
this is what I did so far :
<Padding paddingVertical={isKeyboardOpen ? Spacing.unit : Spacing.small}>
<Button
variant="solid"
label='Next'
style={styles.submitBtn}
/>
</Padding>
And isKeyboardOpen is just a method which will create a listner based on the platform return true if keyboard is open :
Keyboard.addListener(
Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',
true
);
And submitBrn css class is :
submitBtn: {
margin: Spacing.base,
},
First import this packages
import {
Button,
ScrollView,
KeyboardAvoidingView,
TextInput,
} from 'react-native';
Render method
<KeyboardAvoidingView
{...(Platform.OS === 'ios' ? { behavior: 'padding' } : {})}
style={styles.container}>
<ScrollView style={styles.scrollView}>
<TextInput style={styles.input} placeholder="Tap here" />
</ScrollView>
<Button title="Next" />
</KeyboardAvoidingView>
This are the styles
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollView: {
paddingHorizontal: 20,
},
input: {
marginBottom: 20,
borderBottomWidth: 2,
borderColor: '#dbdbdb',
padding: 10,
},
});
Make sure the button is outside the scrollview.
NOTE: You may need to adjust the offset prop of KeyboardAvoidingView if the keyboard has got autocomplete enabled.
Stick button at the bottom of the screen demo
In case anyone is still looking for a solution to this I am posting a working example from October 2021 along with the react native documentation. This example is for a text input that when focused has a button labeled 'Scanner' above the keyboard. React native documentation refers to what we are creating here as a 'toolbar'.
Please see this for further details https://reactnative.dev/docs/next/inputaccessoryview
import {
Button,
ScrollView,
TextInput,
StyleSheet,
InputAccessoryView,
Text,
View,
} from "react-native";
import { MaterialCommunityIcons } from "#expo/vector-icons";
import { BarCodeScanner } from "expo-barcode-scanner";
import { useFocusEffect } from "#react-navigation/native";
function CreateSearchBar() {
const inputAccessoryViewID = "uniqueID";
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const [showScanner, setShowScanner] = useState(false);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === "granted");
})();
}, []);
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
// Useful for cleanup functions
setShowScanner(false);
};
}, [])
);
onChangeSearch = (search) => {};
setScannerShow = (show) => {
setShowScanner(show);
};
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setShowScanner(false);
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
if (showScanner) {
return (
<View style={styles.scanner}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
{scanned && (
<Button
title={"Tap to Scan Again"}
onPress={() => setScanned(false)}
/>
)}
</View>
);
}
return (
<>
<ScrollView keyboardDismissMode="interactive">
<View style={styles.input}>
<MaterialCommunityIcons name="magnify" size={24} color="black" />
<TextInput
onChangeText={onChangeSearch}
inputAccessoryViewID={inputAccessoryViewID}
placeholder="Find items or offers"
/>
<MaterialCommunityIcons
name="barcode"
size={30}
color="black"
onPress={() => setScannerShow(true)}
/>
</View>
</ScrollView>
<InputAccessoryView nativeID={inputAccessoryViewID}>
<Button onPress={() => setScannerShow(true)} title="Scanner" />
</InputAccessoryView>
</>
);
}
const styles = StyleSheet.create({
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
flexDirection: "row",
justifyContent: "space-between",
},
scanner: {
height: "50%",
},
});
export default CreateSearchBar;
YOu can use react native modal
<KeyboardAvoidingView
keyboardVerticalOffset={Platform.OS == "ios" ? 10 : 0}
behavior={Platform.OS == "ios" ? "padding" : "height"} style={{ flex: 1 }} >
<Modal>
<ScrollView>
<Content><-------Your content------></Content>
</ScrollView>
<BottomButton />
</Modal>
</KeyboardAvoidingView>

KeyboardAvoidingView works on EXPO but not on APK?

I bought this Theme which in Expo works flawlessly, but as soon as I build the APK, the Keyboard will cover the whole screen and wont work as supposed.
I'm using expo for testing and it works just fine.
return (
<SafeAreaView style={styles.container}>
<NavHeader title={thread.name} {...{navigation}} />
<FlatList
inverted
data={messages}
keyExtractor={message => `${message.date}`}
renderItem={({ item }) => (
<Msg message={item} name={item.me ? name : thread.name} picture={thread.picture} />
)}
/>
<KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} enabled>
<View style={styles.footer}>
<TextInput
style={styles.input}
placeholder="Write a message"
value={this.state.message}
onChangeText={message => this.setState({ message })}
autoFocus
blurOnSubmit={false}
returnKeyType="send"
onSubmitEditing={this.send}
underlineColorAndroid="transparent"
/>
<TouchableOpacity primary transparent onPress={this.send}>
<Text style={styles.btnText}>Send</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</SafeAreaView>
);
And the Styles
const styles = StyleSheet.create({
container: {
flex: 1
},
footer: {
borderColor: Theme.palette.lightGray,
borderTopWidth: 1,
paddingLeft: Theme.spacing.small,
paddingRight: Theme.spacing.small,
flexDirection: "row",
alignItems: "center"
},
input: {
height: Theme.typography.regular.lineHeight + (Theme.spacing.base * 2),
flex: 1
},
btnText: {
color: Theme.palette.primary
}
});
I have tried the following plugin
using the enableOnAndroid prop
https://github.com/APSL/react-native-keyboard-aware-scroll-view
with no success.
I have posted here:
https://github.com/APSL/react-native-keyboard-aware-scroll-view/issues/305
and here:
https://github.com/expo/expo/issues/2172
Unfortunately this is a known issue
https://github.com/expo/expo/issues/2172
Depending on the complexity of your screen layout you could add a bottom margin or padding using Keyboard listeners provided by React Native.
import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';
class Example extends Component {
componentDidMount () {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow () {
this.setState({
marginBottom: 400
})
}
_keyboardDidHide () {
this.setState({
marginBottom: 0
})
}
render() {
return (
<TextInput
style={{marginBottom: this.state.marginBottom}}
onSubmitEditing={Keyboard.dismiss}
/>
);
}
}