I am trying to place a floating action button in the lower right corner of my app but it is placing it in the top left way off screen.
Returned view:
<View> <View style={{flexDirection: 'row'}}> <TouchableOpacity onPress={this.onPress} activeOpacity={.5} > <Image source={require('./assets/images/hamburger.png')} style={{ width: 30, height: 25, marginLeft: 15}} /> </TouchableOpacity> </View> <FloatingAction style={styles.bottom}/> </View>
Styles:
const styles = StyleSheet.create({ bottom: { flex: 1, position: 'absolute', bottom: 10, right:10 }, });
My current view displays a header and a bottom tab view. I am able to place multiple FAB’s in each tab screen but that produces an undesirable behavior. Thank you for any help.
Edit: What I have:
What I want:
Advertisement
Answer
Your issue was on adding { flex: 1, position: 'absolute',}
to the button style together. The parent component that covers all the phone screen would use flex: 1
, your button component is the one that receives the style for the position.
Always creating a new component makes stuff easier to read and understand. So let’s say you have a button component (<FloatingButton/>
), you would do something like this:
import React from 'react'; import { Text, View, StyleSheet } from 'react-native'; import FloatingButton from './FloatingButton'; export default class App extends React.Component { render() { return ( <View style={styles.container}> <Text> I'm just a Text </Text> <FloatingButton style={styles.floatinBtn} onPress={() => alert(`I'm being clicked!`)} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, floatinBtn: { position: 'absolute', bottom: 10, right: 10, } });
You will get this result:
This is the button component:
import React from 'react'; import { View, TouchableOpacity } from 'react-native'; export default props => ( <TouchableOpacity onPress={props.onPress} style={props.style}> <View style={{ backgroundColor: 'blue', width: 45, height: 45, borderRadius: 45, }} /> </TouchableOpacity> );
Check the snack demo: https://snack.expo.io/@abranhe/floating-btn