I am trying to implement a custom tabbar
in React Native
.
I've done it before with only 2 tabs and it worked. But now I have 4 tabs and it seems to switch between the first and the last tabs only even when I click the second of third ones.
Here is the screenshot of the layout
and here is what happened when I clicked on the second tab
Here is the code for this component
state = {
active: 0,
xTabOne: 0,
xTabTwo: 0,
xTabThree: 0,
xTabFour: 0,
translateX: new Animated.Value(0),
}
handleSlide = type => {
let { active, translateX } = this.state;
Animated.spring(translateX, {
toValue: type,
duration: 100,
}).start()
}
render() {
let { active, xTabOne, xTabTwo, xTabThree, xTabFour, translateX } = this.state;
return (
<Container style={styles.container}>
<StatusBar barStyle="light-content" />
<Text style={styles.topText}>XXXXXXX</Text>
<View style={styles.tabsContainer}>
<Animated.View style={{
position: 'absolute',
width: '25%',
height: '100%',
top: 0,
left: 0,
backgroundColor: '#fff',
borderRadius: 17,
transform: [{ translateX }]
}} />
<TouchableOpacity
style={styles.tabComponent}
onLayout={event => this.setState({
xTabOne: event.nativeEvent.layout.x
})}
onPress={() => this.setState({ active: 0 }, () => this.handleSlide(xTabOne))}
>
<Text style={{ color: active === 0 ? '#0022FF' : '#fff' }}>Back left</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.tabComponent}
onLayout={event => this.setState({
xTabTwo: event.nativeEvent.layout.x
})}
onPress={() => this.setState({ active: 1 }, () => this.handleSlide(xTabTwo))}
>
<Text style={{ color: active === 1 ? '#0022FF' : '#fff' }}>Back right</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.tabComponent}
onLayout={event => this.setState({
xTabTwo: event.nativeEvent.layout.x
})}
onPress={() => this.setState({ active: 2 }, () => this.handleSlide(xTabThree))}
>
<Text style={{ color: active === 2 ? '#0022FF' : '#fff' }}>Front left</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.tabComponent}
onLayout={event => this.setState({
xTabTwo: event.nativeEvent.layout.x
})}
onPress={() => this.setState({ active: 3 }, () => this.handleSlide(xTabFour))}
>
<Text style={{ color: active === 3 ? '#0022FF' : '#fff' }}>Front right</Text>
</TouchableOpacity>
</View>
</Container>
);
}
And here is the style
export default {
container: {
flex: 1,
justifyContent: "flex-start",
paddingTop: 50,
backgroundColor: COLORS.BLUE_COLOR,
flexDirection: 'column',
},
tabsContainer: {
flexDirection: 'row',
marginBottom: 20,
marginLeft: 20,
marginRight: 20,
height: 30,
position: 'relative',
},
tabComponent: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
topText: {
left: 20,
paddingBottom: 20,
fontWeight: 'bold',
fontSize: 20,
color: 'white'
},
}