Related
There is a class components work piece. I want to convert it into a function component and implement it in the same way, but there's a problem.
Unlike the class type, the function type returns to the place where it was created without staying after the picture has moved.
This is the function components.
const [dogs, setDogs] = useState([])
function addDog(){
// setDogs([...dogs, {id: dogCount++}])
dogCount++;
console.log(dogCount)
// console.log(dogs)
const newDog = {id: dogCount, bottom: 125}
setDogs([...dogs, newDog])
}
return (
<View style={styles.entirebottomsheet}>
<View style={styles.container}>
<TouchableOpacity onPress={()=>{addDog();}} style={styles.dogButton}>
<Text>Dog</Text>
</TouchableOpacity>
{dogs.map(dog => {
return (
<DogContainer
key={dog.id}
style={{bottom: dog.bottom, position: 'absolute'}}
/>
);
})}
</View>
</View>
);
function DogContainer () {
const positionX = new Animated.Value(0);
const positionY = new Animated.Value(0);
// DogContainer.defaultProps = {
// onComplete() {}
// }
const getDogStyle = () => ({
transform: [{translateX: positionX}],
});
useEffect(() => {
Animated.spring(positionX, {
duration: 1000,
toValue: width / 3,
easing: Easing.ease,
useNativeDriver: true,
}).start();
Animated.spring(positionY, {
duration: 1000,
toValue: width / 3,
easing: Easing.ease,
useNativeDriver: true,
}).start();
return (
console.log('finish')
)
}, []);
return (
<Animated.View style={[{ bottom: 125},{
transform: [{translateX: positionX}, {translateY: positionY}],
}]}>
<Image source={dogImg} style={{width: 60, height: 60}}/>
</Animated.View>
);
}
This is the class components.
export default class App extends React.Component {
// let {up} = this.props.up;
state = {
dogs: [],
cats: [],
chicks: [],
};
addDog = () => {
console.log(...this.state.dogs);
this.setState(
{
dogs: [
...this.state.dogs,
{
id: dogCount,
bottom: 125,
},
],
},
() => {
dogCount++;
},
);
};
removeDog = id => {
this.setState({
dogs: this.state.dogs.filter(dog => {
return dog.id !== id;
}),
});
};
addCat = () => {
console.log(...this.state.cats);
this.setState(
{
cats: [
...this.state.cats,
{
id: catCount,
bottom: 125,
},
],
},
() => {
catCount++;
},
);
};
removeCat = id => {
this.setState({
cats: this.state.cats.filter(cat => {
return cat.id !== id;
}),
});
};
addChick = () => {
console.log(...this.state.chicks);
this.setState(
{
chicks: [
...this.state.chicks,
{
id: chickCount,
bottom: 125,
},
],
},
() => {
chickCount++;
},
);
};
removeChick = id => {
this.setState({
chicks: this.state.chicks.filter(chick => {
return chick.id !== id;
}),
});
};
render() {
return (
<GestureHandlerRootView>
<View style={styles.entirebottomsheet}>
<View style={styles.container}>
<TouchableOpacity onPress={this.addDog} style={styles.dogButton}>
<Text>Dog</Text>
</TouchableOpacity>
{this.state.dogs.map(dog => {
return (
<DogContainer
key={dog.id}
style={{bottom: dog.bottom, position: 'absolute'}}
onComplete={() => this.removeDog(dog.id)}
/>
);
})}
</View>
<View style={styles.container}>
<TouchableOpacity onPress={this.addCat} style={styles.catButton}>
<Text>Cat</Text>
</TouchableOpacity>
{this.state.cats.map(cat => {
return (
<CatContainer
key={cat.id}
style={{bottom: cat.bottom, position: 'absolute'}}
onComplete={() => this.removeCat(cat.id)}
/>
);
})}
</View>
<View style={styles.container}>
<TouchableOpacity onPress={this.addChick} style={styles.chickButton}>
<Text style={{position: 'absolute'}}>Chick</Text>
</TouchableOpacity>
{this.state.chicks.map(chick => {
return (
<ChickContainer
key={chick.id}
style={{bottom: chick.bottom, position: 'absolute'}}
onComplete={() => this.removeChick(chick.id)}
/>
);
})}
</View>
</View>
</GestureHandlerRootView>
);
}
}
class DogContainer extends React.Component {
state = {
position: new Animated.ValueXY({
x: 0,
y: 0,
}),
};
static defaultProps = {
onComplete() {},
};
componentDidMount() {
Animated.spring(this.state.position.x, {
duration: 1000,
toValue: width / 3,
easing: Easing.ease,
useNativeDriver: true,
}).start(this.props.onComplete);
Animated.spring(this.state.position.y, {
duration: 1000,
toValue: -340,
easing: Easing.ease,
useNativeDriver: true,
}).start(this.props.onComplete);
}
getDogStyle() {
return {
transform: [
{translateY: this.state.position.y},
{translateX: this.state.position.x},
],
};
}
render() {
return (
<Animated.View style={[this.getDogStyle(), this.props.style]}>
<Image source={dogImg} style={{width: 60, height: 60, borderRadius: 30}} />
</Animated.View>
);
}
}
Try to use useRef() hook
function DogContainer () {
const positionX = useRef(new Animated.Value(0)).current;
const positionY = useRef(new Animated.Value(0)).current;
...
In the Class-based version of DogContainer the position coordinate was a part of state.
class DogContainer extends React.Component {
state = {
position: new Animated.ValueXY({
x: 0,
y: 0,
}),
};
static defaultProps = {
onComplete() {},
};
componentDidMount() {
Animated.spring(this.state.position.x, {
duration: 1000,
toValue: width / 3,
easing: Easing.ease,
useNativeDriver: true,
}).start(this.props.onComplete);
Animated.spring(this.state.position.y, {
duration: 1000,
toValue: -340,
easing: Easing.ease,
useNativeDriver: true,
}).start(this.props.onComplete);
}
getDogStyle() {
return {
transform: [
{translateY: this.state.position.y},
{translateX: this.state.position.x},
],
};
}
render() {
return (
<Animated.View style={[this.getDogStyle(), this.props.style]}>
<Image source={dogImg} style={{width: 60, height: 60, borderRadius: 30}} />
</Animated.View>
);
}
}
Function component using the useState hook
function DogContainer ({ onComplete = () => {} }) {
const [position, setPosition] = React.useState(
new Animated.ValueXY({
x: 0,
y: 0,
})
);
const getDogStyle = () => ({
transform: [{
translateX: position.x,
translateY: position.y,
}],
});
useEffect(() => {
Animated.spring(position.x, {
duration: 1000,
toValue: width / 3,
easing: Easing.ease,
useNativeDriver: true,
}).start(onComplete);
Animated.spring(position.y, {
duration: 1000,
toValue: width / 3,
easing: Easing.ease,
useNativeDriver: true,
}).start(onComplete);
console.log('finish');
}, []);
return (
<Animated.View
style={[
{ bottom: 125},
{ transform: [
{ translateX: position.x },
{ translateY: position.y }
],
}
]}
>
<Image source={dogImg} style={{ width: 60, height: 60 }} />
</Animated.View>
);
}
I'm having trouble using the framer-motion-animate-presence component
I'm trying to create a menu navigation system that has sub menus that slide back and forth when they enter or exit but the menu you are currently on does not do its exit animation even though its just the same as the enter animation, I have set up unique keys and ids for all my menu pages so I don't understand why Animate Presence is instantly removing the menu that you navigate from instead of waiting for its animation to finish then removing it.
link to a video displaying the issue
the relevant section of where the dropdown component is used:
<Header sections={["Intro", "What I Do", "About Me"]}
sectionLinks={["#intro", "#what-i-do", "#about-me"]}
logo={ <h4>{"<dev> Finn"}</h4> }
>
<Button icon={ <BsTwitter/> } type="header" link="https://www.youtube.com/watch?v=IF6k0uZuypA&t=842s"/>
<Button icon={ <FaDiscord/> } type="header"/>
<Button icon={ <FiMenu/> } type="header">
<Dropdown key="dropdown"
pages={[
{
name: "main",
items: [
{
text: "Menu",
textType: "title",
},
{
text: "Settings",
buttonType: "navigation",
icon: <RiSettings4Fill/>,
goToPage: "settings",
goToDirection: "right"
}
]
},
{
name: "settings",
items: [
{
text: "Settings",
textType: "bold",
buttonType: "navigation",
icon: <FaArrowLeft/>,
goToPage: "main",
goToDirection: "left"
},
{
text: "Appearance",
toggleType: "theme",
icon: ["🌙", "☀️"],
},
{
text: "Cool Mode",
toggleType: "toggle",
icon: ["😎", "😐"],
}
]
}
]}/>
</Button>
</Header>
The dropdown component: - (the last return statement is where the issue is)
import React, { useEffect, useState, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Button from "./Button";
import Toggle from "./Toggle";
function Dropdown(props) {
const [[activePage, pageDirection], setActivePage] = useState(["main", null]);
const [menuHeight, setMenuHeight] = useState(null);
const dropDownPage = useRef()
function calcHeight() {
const height = dropDownPage.current.offsetHeight
setMenuHeight(height)
}
function DropdownItem(subprops) {
return (
<>
<a className="dropdown__item" onClick={() => {
subprops.goToPage && setActivePage([subprops.goToPage, subprops.goToDirection])
console.log(activePage, pageDirection)
}}>
{subprops.textType === "title" ?
<>
<span className="dropdown__title">{subprops.text}</span>
</> :
<>
{subprops.buttonType === "navigation" ?
<>
<div className="dropdown__button-container">
<Button icon={subprops.icon} type="dropdown"/>
</div>
</> :
<>
{subprops.buttonType === "link" ?
<>
<div className="dropdown__button-container">
<Button icon={subprops.icon} type="dropdown"/>
</div>
</> :
<>
{subprops.toggleType === "theme" ?
<>
<div className="dropdown__toggle-container">
<Toggle icons={subprops.icon} type="theme"/>
</div>
</> :
<>
<div className="dropdown__toggle-container">
<Toggle icons={subprops.icon} type="toggle"/>
</div>
</>
}
</>
}
</>
}
{subprops.textType === "bold" ?
<span className="dropdown__item__text-bold">{subprops.text}</span> :
<span className="dropdown__item__text">{subprops.text}</span>
}
</>
}
</a>
</>
)
}
const dropdownVariants = {
exit: {
x: "150%",
transition: {
type: "spring",
bounce: 0,
damping: 15,
mass: 1,
stiffness: 50,
}
},
enter: {
x: 0,
transition: {
type: "spring",
bounce: 0.3,
damping: 15,
mass: 1,
stiffness: 100
}
}
}
const pageVariants = {
enter: (pageDirection) => {
return {
x: pageDirection === "left" ? "-100%" : pageDirection === "right" ? "100%" : 0,
transition: {
type: "spring",
bounce: 0.3,
damping: 15,
mass: 1,
stiffness: 100
}
}
},
center: {
x: 0,
transition: {
type: "spring",
bounce: 0.3,
damping: 15,
mass: 1,
stiffness: 100
}
},
exit: (pageDirection) => {
return {
x: pageDirection === "left" ? "-100%" : pageDirection === "right" ? "100%" : 0,
transition: {
type: "spring",
bounce: 0.3,
damping: 15,
mass: 1,
stiffness: 100
}
}
}
}
return (
<motion.div className="header__dropdown" style={{ height: menuHeight}} key="header__dropdown"
variants={dropdownVariants}
initial="exit"
animate="enter"
exit="exit"
>
<AnimatePresence custom={pageDirection}>
{props.pages.map((page) => {
return (
<React.Fragment key={page["name"]}>
{activePage === page["name"] &&
<motion.div ref={dropDownPage} id={page["name"]} key={page["name"]}
custom={pageDirection}
variants={pageVariants}
initial="enter"
animate="center"
exit="exit"
>
{page["items"].map((item, index) => {
return (
<DropdownItem key={index}
text={item["text"]}
textType={item["textType"]}
link={item["link"]}
buttonType={item["buttonType"]}
toggleType={item["toggleType"]}
icon={item["icon"]}
goToPage={item["goToPage"]}
goToDirection={item["goToDirection"]}
/>
)
})}
</motion.div>
}
</React.Fragment>
)
})}
</AnimatePresence>
</motion.div>
)
}
export default Dropdown
AnimatePresence will animate its direct children when they are removed from the DOM. In your dropdown component, the direct children of <AnimatePresence> are <React.Fragment> elements that don't look like they are ever actually removed. Do you need those elements for some reason? If you remove them, and have the conditionally rendered motion.div elements as the children (with keys), it should work.
<AnimatePresence custom={pageDirection}>
{props.pages.filter((p) => activePage === p["name"]).map((page) => {
return (
<motion.div ref={dropDownPage} id={page["name"]} key={page["name"]}
custom={pageDirection}
variants={pageVariants}
initial="enter"
animate="center"
exit="exit"
>
{page["items"].map((item, index) => {
return (
<DropdownItem key={index}
text={item["text"]}
textType={item["textType"]}
link={item["link"]}
buttonType={item["buttonType"]}
toggleType={item["toggleType"]}
icon={item["icon"]}
goToPage={item["goToPage"]}
goToDirection={item["goToDirection"]}
/>
)
})}
</motion.div>
)
})}
</AnimatePresence>
I guess you were using fragments because you're mapping through the entire array of pages. I added a filter to reduce the array to just the items that should be rendered before calling map.
I'm using GSAP ScrollTrigger and LocomotiveScroll in a Nuxt application. Everything is working fine so far, except when changing routes.
I guess, I have to kill off and reinitialize LocomotiveScroll and ScrollTrigger?
The relevant JS:
export default {
data() {
return {
lmS: null
};
},
mounted() {
this.lmS = new this.locomotiveScroll({
el: document.querySelector(".js-scroll"),
smooth: true,
direction: "horizontal",
lerp: 0.1,
smartphone: {
smooth: false,
direction: "vertical"
}
});
//////////////////SCROLLTRIGGER SETUP//////////////////
this.lmS.on("scroll", this.$ScrollTrigger.update);
var that = this;
this.$ScrollTrigger.scrollerProxy(".js-scroll", {
scrollTop(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.y;
},
scrollLeft(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.x;
},
getBoundingClientRect() {
return {
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight
};
},
pinType: document.querySelector(".js-scroll").style.transform
? "transform"
: "fixed"
});
this.$ScrollTrigger.addEventListener("refresh", () => this.lmS.update());
this.$ScrollTrigger.refresh(true);
},
destroyed() {
//window.removeEventListener("refresh", () => this.lmS.update());
//let triggers = this.$ScrollTrigger.getAll();
//triggers.forEach((trigger) => {
//trigger.kill(false, true);
//});
this.lmS.destroy();
this.lmS = null;
}
};
I’ve set up a minimal codesandbox:
https://codesandbox.io/s/scrolltrigger-routechange-gv75r?file=/mixins/locomotive.js
Would appreciate any tips! :)
Updated JS:
export default {
data() {
return {
sTrigger: null
lmS: null
};
},
mounted() {
this.lmS = new this.locomotiveScroll({
el: document.querySelector(".js-scroll"),
smooth: true,
direction: "horizontal",
lerp: 0.1,
smartphone: {
smooth: false,
direction: "vertical"
}
});
//////////////////SCROLLTRIGGER SETUP//////////////////
this.sTrigger = this.$ScrollTrigger
this.lmS.on("scroll", this.sTrigger.update);
var that = this;
this.sTrigger.scrollerProxy(".js-scroll", {
scrollTop(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.y;
},
scrollLeft(value) {
return arguments.length
? that.lmS.scrollTo(value, 0, 0)
: that.lmS.scroll.instance.scroll.x;
},
getBoundingClientRect() {
return {
top: 0,
left: 0,
width: window.innerWidth,
height: window.innerHeight
};
},
pinType: document.querySelector(".js-scroll").style.transform
? "transform"
: "fixed"
});
this.sTrigger.addEventListener("refresh", () => this.lmS.update());
this.sTrigger.refresh(true);
},
beforeDestroy(){
window.removeEventListener('refresh', () => this.lmS.update())
let triggers = this.sTrigger.getAll()
triggers.forEach(trigger => {
trigger.kill()
})
this.sTrigger = null
},
destroyed() {
this.lmS.destroy();
this.lmS = null;
}
};
as i am new in react native. i have no much knowledge of class component. i was stuck in code as class components are used in this code but i want to convert them into functional components. anyone please help me to convert this given code into functional component. this is a code of a swipeable card in react native all the given code in class component and use of constructor and this. i want to just convert it into functional component.
//This is an example of Tinder like Swipeable Card//
import React, { Component } from 'react';
//import react in our code.
import {
Platform, StyleSheet, View, Text,
Dimensions, Animated, PanResponder,
} from 'react-native';
//import all the components we are going to use.
const SCREEN_WIDTH = Dimensions.get('window').width;
class SwipeableCard extends React.Component {
constructor() {
super();
this.panResponder;
this.state = {
Xposition: new Animated.Value(0),
RightText: false,
LeftText: false,
};
this.Card_Opacity = new Animated.Value(1);
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => false,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => false,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderMove: (evt, gestureState) => {
this.state.Xposition.setValue(gestureState.dx);
if (gestureState.dx > SCREEN_WIDTH - 250) {
this.setState({
RightText: true,
LeftText: false,
});
} else if (gestureState.dx < -SCREEN_WIDTH + 250) {
this.setState({
LeftText: true,
RightText: false,
});
}
},
onPanResponderRelease: (evt, gestureState) => {
if (
gestureState.dx < SCREEN_WIDTH - 150 &&
gestureState.dx > -SCREEN_WIDTH + 150
) {
this.setState({
LeftText: false,
RightText: false,
});
Animated.spring(
this.state.Xposition,
{
toValue: 0,
speed: 5,
bounciness: 10,
},
{ useNativeDriver: true }
).start();
} else if (gestureState.dx > SCREEN_WIDTH - 150) {
Animated.parallel(
[
Animated.timing(this.state.Xposition, {
toValue: SCREEN_WIDTH,
duration: 200,
}),
Animated.timing(this.Card_Opacity, {
toValue: 0,
duration: 200,
}),
],
{ useNativeDriver: true }
).start(() => {
this.setState({ LeftText: false, RightText: false }, () => {
this.props.removeCard();
});
});
} else if (gestureState.dx < -SCREEN_WIDTH + 150) {
Animated.parallel(
[
Animated.timing(this.state.Xposition, {
toValue: -SCREEN_WIDTH,
duration: 200,
}),
Animated.timing(this.Card_Opacity, {
toValue: 0,
duration: 200,
}),
],
{ useNativeDriver: true }
).start(() => {
this.setState({ LeftText: false, RightText: false }, () => {
this.props.removeCard();
});
});
}
},
});
}
render() {
const rotateCard = this.state.Xposition.interpolate({
inputRange: [-200, 0, 200],
outputRange: ['-20deg', '0deg', '20deg'],
});
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[
styles.card_Style,
{
backgroundColor: this.props.item.backgroundColor,
opacity: this.Card_Opacity,
transform: [
{ translateX: this.state.Xposition },
{ rotate: rotateCard },
],
},
]}>
<Text style={styles.Card_Title}> {this.props.item.card_Title} </Text>
{this.state.LeftText ? (
<Text style={styles.Left_Text_Style}> Left Swipe </Text>
) : null}
{this.state.RightText ? (
<Text style={styles.Right_Text_Style}> Right Swipe </Text>
) : null}
</Animated.View>
);
}
}
export default class App extends React.Component {
constructor() {
super();
this.state = {
Sample_Card_Array: [{
id: '1', card_Title: 'Card 1', backgroundColor: '#FFC107',
}, {
id: '2', card_Title: 'Card 2', backgroundColor: '#ED2525',
}, {
id: '3', card_Title: 'Card 3', backgroundColor: '#E7088E',
}, {
id: '4', card_Title: 'Card 4', backgroundColor: '#00BCD4',
}, {
id: '5', card_Title: 'Card 5', backgroundColor: '#FFFB14',
}],
No_More_Card: false,
};
}
componentDidMount() {
this.setState({
Sample_Card_Array: this.state.Sample_Card_Array.reverse(),
});
if (this.state.Sample_Card_Array.length == 0) {
this.setState({ No_More_Card: true });
}
}
removeCard = id => {
this.state.Sample_Card_Array.splice(
this.state.Sample_Card_Array.findIndex(x => x.id == id),
1
);
this.setState({ Sample_Card_Array: this.state.Sample_Card_Array }, () => {
if (this.state.Sample_Card_Array.length == 0) {
this.setState({ No_More_Card: true });
}
});
};
render() {
return (
<View style={styles.MainContainer}>
{this.state.Sample_Card_Array.map((item, key) => (
<SwipeableCard
key={key}
item={item}
removeCard={this.removeCard.bind(this, item.id)}
/>
))}
{this.state.No_More_Card ? (
<Text style={{ fontSize: 22, color: '#000' }}>No Cards Found.</Text>
) : null}
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingTop: Platform.OS === 'ios' ? 20 : 0,
},
card_Style: {
width: '75%',
height: '45%',
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
borderRadius: 7,
},
Card_Title: {
color: '#fff',
fontSize: 24,
},
Left_Text_Style: {
top: 22,
right: 32,
position: 'absolute',
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'transparent',
},
Right_Text_Style: {
top: 22,
left: 32,
position: 'absolute',
color: '#fff',
fontSize: 20,
fontWeight: 'bold',
backgroundColor: 'transparent',
},
});
the part in the render method is what you return.
to create stateObjects in functional components you will need to use the useState method
const functionalComponent = (props)=>{//props are passed in via props arg...
const defaultState = Xposition: new Animated.Value(0),
RightText: false,
LeftText: false
}
const [state,setState] = useState(defaultState);
... // more stuff
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[
styles.card_Style,
{
backgroundColor: props.item.backgroundColor,
opacity: Card_Opacity,
transform: [
{ translateX: state.Xposition },
{ rotate: rotateCard },
],
},
]}>
<Text style={styles.Card_Title}> {props.item.card_Title} </Text>
{this.state.LeftText ? (
<Text style={styles.Left_Text_Style}> Left Swipe </Text>
) : null}
{this.state.RightText ? (
<Text style={styles.Right_Text_Style}> Right Swipe </Text>
) : null}
</Animated.View>
);
}
you should really go watch some videos on useState, you can be much more granular
to set the state you will need to use the setState method returned from the useState call : setState({..state,{XPosition:55}) or something ... you do the ...state to include the old state values, as the state variable will be overwritten with exactly what you pass in... it wont "update" the existing state it will overwrite it
the next bit is hooking into the functionality in componentDidMount you can do this with useEffect
useEffect(()=>{ // this is setup
// do the stuff from componentDidMount
return ()=>{
// any required teardown can be done here
},[] //[] signifies only do this when component mounts... not every update
);// end useEffect componentDidMount
again there is alot more to useEffect, if you want to do stuff when specific state or props are updated
I am trying to run an expo project Collapsible Header with TabView it works fine in this link.
But when I copy and paste the code to my own expo project, it gives me an error.
Invariant Violation: Element type is invalid: expected a string or a class/function. Check the render method of App
The only thing I changed is class TabView to class App but it is giving me this error.
Also, if I want to build a native code project not expo. How would I run this code? because there is import {Constants } from expo this wouldn't work in react-native run-ios
import * as React from 'react';
import {
View,
StyleSheet,
Dimensions,
ImageBackground,
Animated,
Text
} from 'react-native';
import { Constants } from 'expo';
import { TabViewAnimated, TabBar } from 'react-native-tab-view'; // Version can be specified in package.json
import ContactsList from './components/ContactsList';
const initialLayout = {
height: 0,
width: Dimensions.get('window').width,
};
const HEADER_HEIGHT = 240;
const COLLAPSED_HEIGHT = 52 + Constants.statusBarHeight;
const SCROLLABLE_HEIGHT = HEADER_HEIGHT - COLLAPSED_HEIGHT;
export default class TabView extends React.Component {
constructor(props: Props) {
super(props);
this.state = {
index: 0,
routes: [
{ key: '1', title: 'First' },
{ key: '2', title: 'Second' },
{ key: '3', title: 'Third' },
],
scroll: new Animated.Value(0),
};
}
_handleIndexChange = index => {
this.setState({ index });
};
_renderHeader = props => {
const translateY = this.state.scroll.interpolate({
inputRange: [0, SCROLLABLE_HEIGHT],
outputRange: [0, -SCROLLABLE_HEIGHT],
extrapolate: 'clamp',
});
return (
<Animated.View style={[styles.header, { transform: [{ translateY }] }]}>
<ImageBackground
source={{ uri: 'https://picsum.photos/900' }}
style={styles.cover}>
<View style={styles.overlay} />
<TabBar {...props} style={styles.tabbar} />
</ImageBackground>
</Animated.View>
);
};
_renderScene = () => {
return (
<ContactsList
scrollEventThrottle={1}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.scroll } } }],
{ useNativeDriver: true }
)}
contentContainerStyle={{ paddingTop: HEADER_HEIGHT }}
/>
);
};
render() {
return (
<TabViewAnimated
style={styles.container}
navigationState={this.state}
renderScene={this._renderScene}
renderHeader={this._renderHeader}
onIndexChange={this._handleIndexChange}
initialLayout={initialLayout}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
overlay: {
flex: 1,
backgroundColor: 'rgba(0, 0, 0, .32)',
},
cover: {
height: HEADER_HEIGHT,
},
header: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
zIndex: 1,
},
tabbar: {
backgroundColor: 'rgba(0, 0, 0, .32)',
elevation: 0,
shadowOpacity: 0,
},
});
I got it worked! I had to replace TabViewAnimated to TabView.