I'm trying to use useRef() in one of my compononents in React Native, but I keep getting the
Component Exception: Invalid Hook Call. Hooks can only be called inside of the body of a function component
My component:
import React, { createRef, useRef } from 'react';
import { Animated, View } from 'react-native';
const BottomTabMenu: React.FC = ({ navigation, state: { routeNames } }) => {
const xPosition = useRef(new Animated.Value(0)).current;
return (
<Container>
<Animated.View style={{
position: 'absolute', left: 37, top: 32,
transform: [
{
translateX: xPosition
}
]
}}>
<LinearGradient
start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }}
colors={['#FF151B', '#AA0089']}
style={{
height: 40, width: 50, borderRadius: 20 }}>
</LinearGradient>
</Animated.View>
<BottomTabMenuItem icon={require('../assets/performance.png')} title="Performance" onPress={() => navigation.navigate('Performance')} />
<BottomTabMenuItem icon={require('../assets/wallet.png')} title="Carteira" onPress={() => navigation.navigate('Wallet')} />
<BottomTabMenuItem icon={require('../assets/transactions.png')} title="Extrato" onPress={() => navigation.navigate('Transactions')} />
<BottomTabMenuItem icon={require('../assets/settings.png')} title="Ajustes" onPress={() => navigation.navigate('Settings')} />
</Container>
)
}
I have used useRef in other components without any issue.. This one in particular is a bottom tab tab..
Any help is greatly appreciated!
Turns out I was calling this component in a wrong manner in the BottomTabNavigator component..
BEFORE:
<TabMenu.Navigator initialRouteName="Performance" tabBar={BottomTabMenu}>
<TabMenu.Screen name="Performance" component={Performance} />
<TabMenu.Screen name="Wallet" component={Wallet} />
<TabMenu.Screen name="Transactions" component={Transactions} />
<TabMenu.Screen name="Settings" component={Settings} />
</TabMenu.Navigator>
AFTER:
<TabMenu.Navigator initialRouteName="Performance" tabBar={props => <BottomTabMenu {...props} />}>
<TabMenu.Screen name="Performance" component={Performance} />
<TabMenu.Screen name="Wallet" component={Wallet} />
<TabMenu.Screen name="Transactions" component={Transactions} />
<TabMenu.Screen name="Settings" component={Settings} />
</TabMenu.Navigator>
The piece of code tabBar={props => <BottomTabMenu {...props} />}
did the trick..
Thanks @CharlesKornoelje and @RowanX for helping
Try to do the following:
const xPosition = React.useRef<HTMLElement | null>( new Animated.Value(0)).current
useRef
receives types is the same as the useState hook. You just have to pass it into the <>.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.