im new to react-native and overhelmed with all the options in the www. thats why i'm a bit confused how to complete this task in the best possible way.
i want to make something similar to this, but in react-native. A square-shape, which i can drag all over the view + resize it by dragging it's corners. I already took a look into exponent IDE and the given ThreeView-Component, but i think three.js is a bit over the top for this task, right?
[1]: http://codepen.io/abruzzi/pen/EpqaH
react-native-gesture-handler is the most appropriate thing for your case. I have created minimal example in snack. Here is the minimal code:
let FlatItem = ({ item }) => {
let translateX = new Animated.Value(0);
let translateY = new Animated.Value(0);
let height = new Animated.Value(20);
let onGestureEvent = Animated.event([
{
nativeEvent: {
translationX: translateX,
translationY: translateY,
},
},
]);
let onGestureTopEvent = Animated.event([
{
nativeEvent: {
translationY: height,
},
},
]);
let _lastOffset = { x: 0, y: 0 };
let onHandlerStateChange = event => {
if (event.nativeEvent.oldState === State.ACTIVE) {
_lastOffset.x += event.nativeEvent.translationX;
_lastOffset.y += event.nativeEvent.translationY;
translateX.setOffset(_lastOffset.x);
translateX.setValue(0);
translateY.setOffset(_lastOffset.y);
translateY.setValue(0);
}
};
return (
<View>
<PanGestureHandler onGestureEvent={onGestureTopEvent}>
<Animated.View
style={{
widht: 10,
height,
backgroundColor: 'blue',
transform: [{ translateX }, { translateY }],
}}
/>
</PanGestureHandler>
<PanGestureHandler
onGestureEvent={onGestureEvent}
onHandlerStateChange={onHandlerStateChange}>
<Animated.View
style={[
styles.item,
{ transform: [{ translateX }, { translateY }] },
]}>
<Text>{item.id}</Text>
</Animated.View>
</PanGestureHandler>
</View>
);
};
let data = [
{ key: 1, id: 1 },
];
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<FlatItem item={data[0]} />
</View>
);
}
}
Here is the snack link if you want to test! PS: I have made only top resizing. The rest is for you to do! It should be enough to understand the way how to it!
Related
I am using react-spring lib. in the react-native application. I have archived most of animation but I can not figure out how to use rotate init.
Here is my current code =>
<Spring
from={ { width: '100%', resizeMode: "contain", rotate: 0 } }
to={ { rotate: 360 } }
loop
config={ { duration: 1500 } }
>
{({ rotate, ...props }) => (
<AnimatedImage source={img} style={ {...props, transform: [{ rotate: `${rotate}deg` }]} } />
)}
</Spring>
Then get a error Like this =>
TypeError: undefined is not a function (near '...transform.forEach...')
If someone can explain how to achieve the rotate animation with react-spring it would be really helpful.
you can find a simple example here
You can achieve the rotation animation in #react-spring/native by using the interpolations methods.
const AnimatedImage = animated(Image)
const App = () => {
const { rotate } = useSpring({
from: { rotate: 0 },
to: { rotate: 1 },
loop: { reverse: true },
config: { duration: 1500 }
})
return (
<AnimatedImage source={img} style={{ transform: [ { rotate: rotate.to([0, 1], ['0deg', '360deg']) } ] }} />
);
};
It is strange that we can not apply rotation directly, but i haven't found any other method other than this one in #react-spring/native
react-spring/native it's web based library maybe it's work but there's no clear way for it, but on the other hand you can archive this animation using native Animated like this:
const App: () => Node = () => {
const spinValue = new Animated.Value(0);
const spin = () => {
spinValue.setValue(0);
Animated.timing(spinValue, {
toValue: 1,
duration: 1500,
easing: Easing.linear,
useNativeDriver: true,
}).start(() => spin());
};
useEffect(() => {
spin();
}, []);
const rotate = spinValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg'],
});
return (
<SafeAreaView>
<View style={styles.container}>
<Animated.View style={{transform: [{rotate}]}}>
<AntDesign name={'loading1'} color={'blue'} size={50} />
</Animated.View>
</View>
</SafeAreaView>
);
};
you can check this working example from here.
and here's a repo on github with a working react native project also from here.
Hope it helps you :D
I have a ScrollView and I want to have a View with background color white, then if scroll position is more than 0 change it to transparent, and back to white if scroll goes back to 0.
I tried to get started but react native animations seem crazy complicated coming back from a vue.js background.
Here is my code:
const [animation, setAnimation] = useState(new Animated.Value(0))
const handleScroll = (event) => {
console.log(event.nativeEvent.contentOffset.y);
var scroll = event.nativeEvent.contentOffset.y;
if(scroll > 0)
{
handleAnimation();
}
};
const boxInterpolation = animation.interpolate({
inputRange: [0, 1],
outputRange:["rgb(255,255,255)" , "rgba(255,255,255,0)"]
})
const animatedStyle = {
backgroundColor: boxInterpolation
}
const handleAnimation = () => {
Animated.timing(animation, {
toValue:1,
duration: 1000,
useNativeDriver: true
}).start();
};
And my views
<ScrollView showsVerticalScrollIndicator={false} scrollEventThrottle={16} onScroll={handleScroll} style={{flex:1,backgroundColor:'white',position:'relative'}}>
<View style={{ width:'100%', height:505,position:'relative' ,backgroundColor:'red}}>
</View>
</ScrollView>
<Animated.View style={{width:'100%',height:100,...animatedStyle, flexDirection:'row',justifyContent:'space-around',alignItems:'center',position:'absolute',bottom:0,left:0}}>
</Animated.View>
The recommend way of getting the ScrollView x and y position is this below
const scrolling = React.useRef(new Animated.Value(0)).current;
<Animated.ScrollView
onScroll={Animated.event(
[{
nativeEvent: {
contentOffset: {
y: scrolling,
},
},
}],
{ useNativeDriver: false },
)}
</Animated.View>
Now everything works heres a full example (https://snack.expo.dev/#heytony01/ca5000) must be run a phone not web. And below is the code.
import React from 'react';
import { Button,View,Animated,ScrollView } from 'react-native';
export default function App() {
const scrolling = React.useRef(new Animated.Value(0)).current;
const boxInterpolation = scrolling.interpolate({
inputRange: [0, 100],
outputRange:["rgb(255,255,255)" , "rgba(255,255,255,0)"],
})
const animatedStyle = {
backgroundColor: boxInterpolation
}
return (
<View style={{flex:1}}>
<Animated.ScrollView showsVerticalScrollIndicator={false} scrollEventThrottle={16} style={{flex:1,backgroundColor:'black',position:'relative'}}
onScroll={Animated.event(
[{
nativeEvent: {
contentOffset: {
//
y: scrolling,
},
},
}],
{ useNativeDriver: false },
)}
>
<View style={{ width:'100%', height:505,position:'relative', backgroundColor:'red'}}>
</View>
</Animated.ScrollView>
<Animated.View style={{width:'100%',height:100,...animatedStyle, flexDirection:'row',justifyContent:'space-around',alignItems:'center',position:'absolute',bottom:0,left:0,zIndex:1}}>
</Animated.View>
</View>
);
}
Also if you want to print the animated values when debugging you can do this
React.useEffect(()=>{
scrolling.addListener(dic=>console.log(dic.value))
return ()=> scrolling.removeAllListeners()
},[])
How can I do a similar oval scroll?
What can I use for this?
Based on the assumption that you want something like this, I wrote a simple example
If someday the link turns out to be broken, below I attach the code additionally
import React, { useCallback, useState, useRef } from "react";
import {
FlatList,
Text,
View,
StyleSheet,
Dimensions,
Animated
} from "react-native";
const { height } = Dimensions.get("window");
const screenMiddle = height / 2;
const itemScaleOffset = height / 3;
const DATA = new Array(20).fill(0).map((...args) => ({
id: args[1],
title: args[1]
}));
// args[1] is an index, just I hate warnings
const Item = ({ title, offsetY }) => {
const [scrollEdges, setScrollEdges] = useState({
top: 0,
middle: 0,
bottom: 0
});
const onLayout = useCallback(
({
nativeEvent: {
layout: { top, height }
}
}) =>
setScrollEdges((edges) => ({
...edges,
top: top - itemScaleOffset - screenMiddle,
middle: top + height / 2 - screenMiddle,
bottom: top + height + itemScaleOffset - screenMiddle
})),
[]
);
const scale = offsetY.interpolate({
inputRange: [scrollEdges.top, scrollEdges.middle, scrollEdges.bottom],
outputRange: [0.66, 1, 0.66],
extrapolate: "clamp"
});
return (
<Animated.View
onLayout={onLayout}
style={[
{
transform: [
{
scale
}
]
},
styles.item
]}
>
<Text style={styles.title}>{title}</Text>
</Animated.View>
);
};
const keyExtractor = ({ id }) => id.toString();
const App = () => {
const offsetY = useRef(new Animated.Value(0)).current;
const renderItem = useCallback(
({ item: { title } }) => <Item title={title} offsetY={offsetY} />,
[offsetY]
);
return (
<View style={styles.app}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={keyExtractor}
onScroll={Animated.event(
[
{
nativeEvent: {
contentOffset: {
y: offsetY
}
}
}
],
{
useNativeDriver: false
}
)}
/>
</View>
);
};
const styles = StyleSheet.create({
app: {
flex: 1
},
item: {
backgroundColor: "#f9c2ff",
padding: 20,
marginVertical: 8,
marginHorizontal: 16
},
title: {
fontSize: 32
}
});
export default App;
I think you should use Reanimated 2 who has a very easy sintaxis and also very powerful. Maybe in combination with RNGestureHandler.
I am actually rendering a Complex UI in a react-native app. I am using react-navigation. Whenever I click the option in navigation drawer for my complex UI Page, the whole app hangs for 3-5 seconds and then the page is shown. What I want is a loader screen that loads immediately when I click on the option in navigation drawer and when the complex UI is rendered the loader should disappear and the UI should be shown. The app freezes because of the rendering of the UI. Is there any way to asynchronously render the UI after displaying the loading screen?
Edit
Below is the complex UI that I mentioned earlier. This table is loaded when I navigate to this page.
// source https://snack.expo.io/#shrey/highly-responsive-sheet
import React from "react"
import { Animated, ActivityIndicator, FlatList, ScrollView, StyleSheet, Text, View,TouchableOpacity } from "react-native"
const NUM_COLS = 15
const NUM_ROWS_STEP = 20
const CELL_WIDTH = 100
const CELL_HEIGHT = 60
const black = "#000"
const white = "#fff"
const styles = StyleSheet.create({
container: { backgroundColor: white, marginVertical: 40, marginBottom: 80 },
header: { flexDirection: "row", borderTopWidth: 1, borderColor: black },
identity: { position: "absolute", width: CELL_WIDTH },
body: { marginLeft: CELL_WIDTH },
cell: {
width: CELL_WIDTH,
height: CELL_HEIGHT,
borderRightWidth: 1,
borderBottomWidth: 1,
borderColor: black,
},
column: { flexDirection: "column" },
})
class Sheet extends React.Component {
constructor(props: {}) {
super(props)
this.headerScrollView = null
this.scrollPosition = new Animated.Value(0)
this.scrollEvent = Animated.event(
[{ nativeEvent: { contentOffset: { x: this.scrollPosition } } }],
{ useNativeDriver: false },
)
this.state = { count: NUM_ROWS_STEP, loading: false }
}
handleScroll = e => {
if (this.headerScrollView) {
let scrollX = e.nativeEvent.contentOffset.x
this.headerScrollView.scrollTo({ x: scrollX, animated: false })
}
}
scrollLoad = () => this.setState({ loading: false, count: this.state.count + NUM_ROWS_STEP })
handleScrollEndReached = () => {
if (!this.state.loading) {
this.setState({ loading: true }, () => setTimeout(this.scrollLoad, 500))
}
}
formatCell(value) {
return (
<TouchableOpacity onPress=()>
<View key={value} style={styles.cell}>
<Text>{value}</Text>
</View>
</TouchableOpacity>
)
}
formatColumn = (section) => {
let { item } = section
let cells = []
for (let i = 0; i < this.state.count; i++) {
cells.push(this.formatCell(`col-${i}-${item.key}`))
}
return <View style={styles.column}>{cells}</View>
}
formatHeader() {
let cols = []
for (let i = 0; i < NUM_COLS; i++) {
cols.push(this.formatCell(`frozen-row-${i}`))
}
return (
<View style={styles.header}>
{this.formatCell("frozen-row")}
<ScrollView
ref={ref => (this.headerScrollView = ref)}
horizontal={true}
scrollEnabled={false}
scrollEventThrottle={16}
>
{cols}
</ScrollView>
</View>
)
}
formatIdentityColumn() {
let cells = []
for (let i = 0; i < this.state.count; i++) {
cells.push(this.formatCell(`frozen-col-${i}`))
}
return <View style={styles.identity}>{cells}</View>
}
formatBody() {
let data = []
for (let i = 0; i < NUM_COLS; i++) {
data.push({ key: `content-${i}`})
}
return (
<View>
{this.formatIdentityColumn()}
<FlatList
style={styles.body}
horizontal={true}
data={data}
renderItem={this.formatColumn}
stickyHeaderIndices={[0]}
onScroll={this.scrollEvent}
scrollEventThrottle={16}
extraData={this.state}
/>
</View>
)
}
formatRowForSheet = (section) => {
let { item } = section
return item.render
}
componentDidMount() {
this.listener = this.scrollPosition.addListener(position => {
this.headerScrollView.scrollTo({ x: position.value, animated: false })
})
}
render () {
let body = this.formatBody()
let data = [{ key: "body", render: body }]
return (
<View style={styles.container}>
{this.formatHeader()}
<FlatList
data={data}
renderItem={this.formatRowForSheet}
onEndReached={this.handleScrollEndReached}
onEndReachedThreshold={.005}
/>
{this.state.loading && <ActivityIndicator />}
</View>
)
}
}
export default Sheet
Your UI probably also loads slowly because you are using a FlatList inside a FlatList. In my experience it will only cause confussion and performance issues.
One thing you might also want to do is integrate with something like Redux, to handle a global loading state, and based on that value you show a loading spinner or the data.
Without seeing actual code, I can only suggest high-level solutions:
Consider using requestAnimationFrame or InteractionManager to schedule expensive calculations.
Render the loading state first, then listen to navigation focus event to start rendering your Complex UI.
Remember to test in production mode, because the difference with development can be signification.
Links to the concepts I mentioned:
https://facebook.github.io/react-native/docs/performance#my-touchablex-view-isn-t-very-responsive
https://facebook.github.io/react-native/docs/timers#interactionmanager
https://reactnavigation.org/docs/en/navigation-events.html
How can I create a collapsible or accordion component with using 'only' native-base library.
Here is solution that worked for me:
'use strict'
import React from 'react';
import {
AppRegistry,
Animated,
Dimensions,
Easing,
Image,
ImageBackground,
Text,
View,
StyleSheet,
TouchableOpacity,
ScrollView
} from 'react-native';
const categoryLinks = [ //for the sake of simplicity, we use the same set of category links for all touts
{label: 'Subcategory1'},
{label: 'Subcategory2'},
{label: 'Subcategory3'},
{label: 'Subcategory4'},
{label: 'Subcategory5'},
{label: 'Subcategory6'},
{label: 'Subcategory7'},
{label: 'Subcategory8'},
{label: 'Subcategory9'},
{label: 'Subcategory10'},
]
const categoryTouts = [ //the touts are the clickable image items that hold our links
{image: require('../assets/images/some_image.png'), title: 'Category1', links: categoryLinks},
{image: require('../assets/images/some_image.png'), title: 'Category2', links: categoryLinks},
{image: require('../assets/images/some_image.png'), title: 'Category3', links: categoryLinks},
]
const SUBCATEGORY_FADE_TIME = 400 //time in ms to fade in / out our subcategories when the accordion animates
const SUBCATEGORY_HEIGHT = 40 //to save a costly measurement process, we know our subcategory items will always have a consistent height, so we can calculate how big the overall subcategory container height needs to expand to by multiplying this by the number of items
const CONTAINER_PADDING_TOP = 40 //to leave room for the device battery bar
const categoryLinksLength = categoryLinks.length //number of subcategory items - if we werent using the same set of links for all touts, we would need to store this within each tout class probably, to know how big each container should expand to to show all the links
const subcategoryContainerHeight = categoryLinksLength * SUBCATEGORY_HEIGHT //total height for the container
export class CategoryLinks extends React.PureComponent { //using PureComponent will prevent unnecessary renders
toutPositions = [] //will hold the measured offsets of each tout when unexpanded
render() {
return (
<Animated.View //view should be animated because its opacity will change
style={{position: 'absolute', top: 0, left: 0, opacity: this.props.subcategoryOpacity}}
>
<View>
{
this.props.links && this.props.links.map((link, index, links) => { //render our subcategory links
return (
<View
key={link.label}
>
<Text style={styles.subcategoryLinks}>{link.label}</Text>
</View>
)
})
}
</View>
</Animated.View>
)
}
}
export class Tout extends React.PureComponent { //using PureComponent will prevent unnecessary renders
state = {
toutSubcategoriesVisible: false, //true when we the tout has been clicked on and subcategory items are exposed
}
animatedValue = new Animated.Value(0) //we will animate this value between 0 and 1 to hide and show the subcategories
animCategoryHeight = this.animatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, subcategoryContainerHeight], //when animated value is 1, the subcategory container will be equal to the number of links * each links height
})
subcategoryOpacity = new Animated.Value(0) //separate animated value for each subcategory list's opacity, as we will animate this independent of the height
measurements = {} //will hold each tout's location on the page so that we can automatically scroll it to the top of our view
measureToutRef = () => {
this.toutRef.measure((x, y, width, height, pageX, pageY) => { //measuring gives us all of these properties, so we must capture them and pass down only the two we need
this.measurements.pageY = pageY //Y position in the overall view
this.measurements.height = height //height of the tout (really this is the same among all touts in our example, but we will allow our touts to have different heights this way)
this.props.handleLayout(this.measurements, this.props.toutIndex) //pass this back to the parent (scrollAccordion)
})
}
handlePressTout = () => {
if (this.props.links && this.props.links.length) { //if the tout has subcategory links, hide or show them based on the current state
const toutSubcategoriesVisible = this.state.toutSubcategoriesVisible
if (toutSubcategoriesVisible) {
this.hideToutSubcatgories()
}
else {
this.showToutSubcatgories()
}
}
}
showToutSubcatgories = () => {
this.setState({toutSubcategoriesVisible: true})
Animated.timing(this.animatedValue, { //animating this value from zero to one will update the subcategory container height, which interpolates this value
toValue: 1,
duration: SUBCATEGORY_FADE_TIME,
easing: Easing.inOut(Easing.quad),
}).start(() => {
this.props.handlePressTout(this.props.toutIndex)
})
Animated.timing(this.subcategoryOpacity, {
toValue: 1,
duration: SUBCATEGORY_FADE_TIME,
easing: Easing.inOut(Easing.quad),
}).start()
}
hideToutSubcatgories = () => {
Animated.timing(this.animatedValue, {
toValue: 0,
duration: SUBCATEGORY_FADE_TIME,
easing: Easing.inOut(Easing.quad),
}).start(() => {
this.setState({toutSubcategoriesVisible: false})
})
Animated.timing(this.subcategoryOpacity, {
toValue: 0,
duration: SUBCATEGORY_FADE_TIME,
easing: Easing.inOut(Easing.quad),
}).start()
}
setToutRef = node => { //store a reference to the tout so we can measure it
if (node) {
this.toutRef = node
}
}
render() {
let categoryLinks
if (this.props.links && this.props.links.length) { //if the tout has links, render them here
categoryLinks = (
<Animated.View
style={{height: this.animCategoryHeight}}
>
<CategoryLinks {...this.props} isVisible={this.state.toutSubcategoriesVisible}
subcategoryOpacity={this.subcategoryOpacity}/>
</Animated.View>
)
} else {
categoryLinks = null
}
return (
<View
style={this.props.toutIndex === 0 ? {marginTop: 0} : {marginTop: 5}} //if this is the first tout, no margin is needed at top
onLayout={!this.measurements.pageY ? this.measureToutRef : () => null} //if we already have measurements for this tout, no need to render them again. Otherwise, get the measurements
>
<TouchableOpacity
ref={this.setToutRef}
onPress={this.handlePressTout}
>
<ImageBackground
source={this.props.image}
style={styles.toutImage}
width={'100%'}
>
<Text
style={styles.toutText} //text is wrapped by image so it can be easily centered
>
{this.props.title}
</Text>
</ImageBackground>
</TouchableOpacity>
{categoryLinks}
</View>
)
}
}
AppRegistry.registerComponent('Tout', () => Tout);
export default class scrollAccordion extends React.PureComponent { //scroll accordion is our parent class - it renders the touts and their subcategories
measurements = []
handlePressTout = (toutIndex) => { //when we press a tout, animate it to the top of the screen and reveal its subcategoires
this.scrollViewRef.scrollTo({
y: this.measurements[toutIndex].pageY - CONTAINER_PADDING_TOP,
})
}
setScrollRef = node => { //store a reference to the scroll view so we can call its scrollTo method
if (node) {
this.scrollViewRef = node
}
}
handleLayout = (measurements, toutIndex) => { //this process is expensive, so we only want to measure when necessary. Probably could be optimized even further...
if (!this.measurements[toutIndex]) { //if they dont already exist...
this.measurements[toutIndex] = measurements //...put the measurements of each tout into its proper place in the array
}
}
render() {
console.log('render')
return (
<View style={styles.container}>
<ScrollView
scrollEventThrottle={20} //throttling the scroll event will decrease the amount of times we store the current scroll position.
ref={this.setScrollRef}
>
<View>
{
categoryTouts.map((tout, index) => {
return (
<Tout
key={index}
toutIndex={index} //tout index will help us know which tout we are clicking on
{...tout}
handleLayout={this.handleLayout} //when layout is triggered for touts, we can measure them
handlePressTout={this.handlePressTout}
/>
)
})
}
</View>
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: CONTAINER_PADDING_TOP,
backgroundColor: 'white',
},
toutText: {
color: 'white', backgroundColor: 'transparent', fontWeight: 'bold', fontSize: 24
},
toutImage: {
alignItems: 'center', justifyContent: 'center'
},
subcategoryLinks: {
lineHeight: 40,
}
});
AppRegistry.registerComponent('scrollAccordion', () => scrollAccordion);