React Native - Floating Action Button - Mobile Application Development
Felicitations! You are standing in the right place! Today, we will show you how to Add a Floating Action Button to Mobile App.
Our starting screen will look like this −
Implementation
First, You must set up your local development environment. Follow the below link to set up your local environment.
After executing the commands mentioned in this link, a folder with a specified name is created with the following contents.
import React from 'react';
import { StyleSheet, View, Image, TouchableOpacity, Alert } from 'react-native';
Create a function named as MyFunction(). We would call this function on the Floating Action Button onPress event.
MyFunction = () => {
Alert.alert("Wow! Floating Button Clicked");
}
Engender a Root View in render’s return block.
render() {
return (
<View style={styles.container}>
<TouchableOpacity activeOpacity={0.5} onPress={this.MyFunction}
style={styles.TouchableOpacityStyle} >
<Image source={{ uri: 'https://raw.githubusercontent.com/knowledgefactory4u
/Javascript/master/floatingButton.jpeg' }}
style={styles.FloatingButtonStyle} />
</TouchableOpacity>
</View>
);
}
}
Engender Style for View, TouchableOpacity, and Image component.
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white'
},
TouchableOpacityStyle: {
position: 'absolute',
width: 70,
height: 70,
alignItems: 'center',
justifyContent: 'center',
right: 30,
bottom: 30,
},
FloatingButtonStyle: {
resizeMode: 'contain',
width: 70,
height: 70,
}
});
Complete source code for App.js File
import React from 'react';
import { StyleSheet, View, Image, TouchableOpacity, Alert } from 'react-native';
export default class App extends React.Component {
MyFunction = () => {
Alert.alert("Wow! Floating Button Clicked");
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity activeOpacity={0.5} onPress={this.MyFunction} style=
{styles.TouchableOpacityStyle} >
<Image source={{ uri: 'https://raw.githubusercontent.com/knowledgefactory4u
/Javascript/master/floatingButton.jpeg' }}
style={styles.FloatingButtonStyle} />
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white'
},
TouchableOpacityStyle: {
position: 'absolute',
width: 70,
height: 70,
alignItems: 'center',
justifyContent: 'center',
right: 30,
bottom: 30,
},
FloatingButtonStyle: {
resizeMode: 'contain',
width: 70,
height: 70,
}
});
First, You must set up your local development environment. Follow the below link to set up your local environment.
Run
sibinmuhammed@ladmin-H310M-S2:~$ react-native start
sibinmuhammed@ladmin-H310M-S2:~/knf-reactnative/KnowledgeFactoryDemo$ react-native run-android