ReactNative Pressable align text to center - react-native

I'd like align text to center in a Pressable element, but doesn't work for me.
import React from 'react';
import { StyleSheet, Pressable, GestureResponderEvent, PressableProps, Text } from 'react-native';
interface MyButtonProps extends PressableProps {
key: number;
uri: string;
title: string;
}
export default class MyButton extends React.Component<MyButtonProps, {}> {
_onPressButton = (uri: string) => {
fetch(uri).then((res) => {
console.log(res);
}).catch((e) => console.log(e));
};
render() {
const { onPress, ...rest } = this.props;
return (
<Pressable style={({ pressed }) => [
{
backgroundColor: pressed ? '#3F8f7F' : '#318ce7',
}, styles.pressableStyle]}
onPress={(event: GestureResponderEvent) => {
this._onPressButton(this.props.uri);
if (onPress !== undefined && onPress !== null) {
onPress(event);
}
}}
{...rest}
>
<Text style={styles.titleStyle}>{this.props.title}</Text>
</Pressable>
);
}
}
const styles = StyleSheet.create({
titleStyle: {
color: 'white',
fontSize: 30,
},
pressableStyle: {
alignContent: 'center',
justifyContent: 'center',
height: 100,
borderRadius: 10
},
})
Text is aligned to left not center. How can I align content properly? Please help me.
(I type more to this post to accept not as a code only I dont understand why)

There is couple things you can do. Did you try textAling:'center' to your title?. Maybe give width to your title.

I solved the problem:
titleStyle: {
color: 'white',
fontSize: 30,
textAlign: 'center'
},

Related

How to remove submitted text input on React Native?

My code is working fine, it's pushing all the data to firebase as it should. I'm having no problems at all.
I just want to implement to remove the submitted data in text input. Since it stays there and you have to remove it manually.
I've been trying to add another function to 'onPress' to clear the inputs, but I can't seem to make it work. Any advice or help will be more than welcome.
Please check my code here below.
import { useState } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
import { addDoc, collection, doc, setDoc } from "firebase/firestore";
import { db } from './components/config';
export default function App() {
const [nombre, setNombre] = useState('');
const [cantidad, setCantidad] = useState('');
const [pretexto, setPretexto] = useState('');
function create(){
//Submit data
addDoc(collection(db, "users"), {
nombre: nombre,
cantidad: cantidad,
pretexto: pretexto
}).then(() => {
console.log('Data submitted');
}).catch((error) => {
console.log(error);
})
}
return (
<View style={styles.container}>
<View style={styles.textBox}>
<TextInput value ={nombre} onChangeText={(nombre) => {setNombre(nombre)}} placeholder='Nombre del caretubo' style={styles.inputOne}></TextInput>
<TextInput value={cantidad} onChangeText={(cantidad) => {setCantidad(cantidad)}} placeholder='Cantidad que debe el HP' style={styles.inputTwo}></TextInput>
<TextInput value={pretexto} onChangeText={(pretexto) => {setPretexto(pretexto)}} placeholder='Pretexto' style={styles.inputThree}></TextInput>
<TouchableOpacity style={styles.botonaso} onPress={() => {create; setNombre(''); }}>
<Text style={styles.botonasoTexto}>Subir</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
textBox: {
width: '100%',
padding: 12,
borderColor: 'gray',
borderWidth: 1,
borderRadius: 20,
},
inputOne: {
fontSize: 15,
},
inputTwo: {
fontSize: 15,
},
inputThree: {
fontSize: 15
},
botonaso: {
backgroundColor: '#202A44',
alignItems: 'center',
borderRadius: 20,
padding: 10
},
botonasoTexto: {
color: 'white'
}
});
const clearTextInputs = () => {
setNombre('');
setCantidad('');
setPretexto('');
};
function create() {
//Submit data
addDoc(collection(db, "users"), {
nombre: nombre,
cantidad: cantidad,
pretexto: pretexto
}).then(() => {
console.log('Data submitted');
clearTextInputs(); // <---------- add here
}).catch((error) => {
console.log(error);
})
}
<TouchableOpacity style={styles.botonaso} onPress={create}> // <----- onPress here
<Text style={styles.botonasoTexto}>Subir</Text>
</TouchableOpacity>

How to make a QR code scanner in React native using expo?

When I run https://snack.expo.io/#sushil62/qr-code-scanner in the expo which works fine, but when copy the same code given in App.js file, after running the application the camera opens but it shows no result while scanning, and
in expo also when changing the snack version 33 or higher it does not work there too.
import React, { Component } from 'react';
import { Alert, Linking, Dimensions, LayoutAnimation, Text, View, StatusBar, StyleSheet, TouchableOpacity } from 'react-native';
import { BarCodeScanner, Permissions } from 'expo';
export default class App extends Component {
state = {
hasCameraPermission: null,
lastScannedUrl: null,
};
componentDidMount() {
this._requestCameraPermission();
}
_requestCameraPermission = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted',
});
};
_handleBarCodeRead = result => {
if (result.data !== this.state.lastScannedUrl) {
LayoutAnimation.spring();
this.setState({ lastScannedUrl: result.data });
}
};
render() {
return (
<View style={styles.container}>
{this.state.hasCameraPermission === null
? <Text>Requesting for camera permission</Text>
: this.state.hasCameraPermission === false
? <Text style={{ color: '#fff' }}>
Camera permission is not granted
</Text>
: <BarCodeScanner
onBarCodeRead={this._handleBarCodeRead}
style={{
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}}
/>}
{this._maybeRenderUrl()}
<StatusBar hidden />
</View>
);
}
_handlePressUrl = () => {
Alert.alert(
'Open this URL?',
this.state.lastScannedUrl,
[
{
text: 'Yes',
onPress: () => Linking.openURL(this.state.lastScannedUrl),
},
{ text: 'No', onPress: () => {} },
],
{ cancellable: false }
);
};
_handlePressCancel = () => {
this.setState({ lastScannedUrl: null });
};
_maybeRenderUrl = () => {
if (!this.state.lastScannedUrl) {
return;
}
return (
<View style={styles.bottomBar}>
<TouchableOpacity style={styles.url} onPress={this._handlePressUrl}>
<Text numberOfLines={1} style={styles.urlText}>
{this.state.lastScannedUrl}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.cancelButton}
onPress={this._handlePressCancel}>
<Text style={styles.cancelButtonText}>
Cancel
</Text>
</TouchableOpacity>
</View>
);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
bottomBar: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 15,
flexDirection: 'row',
},
url: {
flex: 1,
},
urlText: {
color: '#fff',
fontSize: 20,
},
cancelButton: {
marginLeft: 10,
alignItems: 'center',
justifyContent: 'center',
},
cancelButtonText: {
color: 'rgba(255,255,255,0.8)',
fontSize: 18,
},
});
It would be very nice if someone suggests me to solve this or give me an example(such as downgrading the expo version) so that I can implement this.
You can use
expo-barcode-scanner
Run expo install expo-barcode-scanner
Usage
You must request permission to access the user's camera before attempting to get it. To do this, you will want to use the Permissions API. You can see this in practice in the following example.
import * as React from 'react';
import {
Text,
View,
StyleSheet,
Button
} from 'react-native';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';
import {
BarCodeScanner
} from 'expo-barcode-scanner';
export default class BarcodeScannerExample extends React.Component {
state = {
hasCameraPermission: null,
scanned: false,
};
async componentDidMount() {
this.getPermissionsAsync();
}
getPermissionsAsync = async() => {
const {
status
} = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted'
});
};
render() {
const {
hasCameraPermission,
scanned
} = this.state;
if (hasCameraPermission === null) {
return <Text > Requesting
for camera permission < /Text>;
}
if (hasCameraPermission === false) {
return <Text > No access to camera < /Text>;
}
return ( <
View style = {
{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
}
} >
<
BarCodeScanner onBarCodeScanned = {
scanned ? undefined : this.handleBarCodeScanned
}
style = {
StyleSheet.absoluteFillObject
}
/>
{
scanned && ( <
Button title = {
'Tap to Scan Again'
}
onPress = {
() => this.setState({
scanned: false
})
}
/>
)
} <
/View>
);
}
handleBarCodeScanned = ({
type,
data
}) => {
this.setState({
scanned: true
});
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
};
}
Note: Passing undefined to the onBarCodeScanned prop will result in no scanning. This can be used to effectively "pause" the scanner so that it doesn't continually scan even after data has been retrieved.
Allow all the permisions which gets popped.
You're good to go!!
Hope this helps.

How to implement swiping to access different navigation screens in React Native?

I am trying to build an interface similar to the Snapchat's interface where you can swipe left/right/up to access different screen/navigator. Currently I am using the DrawerNavigator but it's kind of janky because I am using a DrawerNavigator on top of another DrawerNavigator.
Does anyone have a good suggestion on the best way to do this?
Thanks!
The following code is implementing easy 4-way swipe navigation across views declaratively in under 20 lines, no Javascript!
import Swiper from 'react-native-swiper'
import randomcolor from 'randomcolor'
const {
View,
Text,
StyleSheet
} = React
var styles = StyleSheet.create({
container: {
flex: 1
},
view: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
})
class TitleText extends React.Component {
render() {
return (
<Text style={{ fontSize: 48, color: 'white' }}>
{this.props.label}
</Text>
)
}
}
class Home extends React.Component {
viewStyle() {
return {
flex: 1,
backgroundColor: randomcolor(),
justifyContent: 'center',
alignItems: 'center',
}
}
render() {
return (
<Swiper
loop={false}
showsPagination={false}
index={1}>
<View style={this.viewStyle()}>
<TitleText label="Left" />
</View>
<Swiper
horizontal={false}
loop={false}
showsPagination={false}
index={1}>
<View style={this.viewStyle()}>
<TitleText label="Top" />
</View>
<View style={this.viewStyle()}>
<TitleText label="Home" />
</View>
<View style={this.viewStyle()}>
<TitleText label="Bottom" />
</View>
</Swiper>
<View style={this.viewStyle()}>
<TitleText label="Right" />
</View>
</Swiper>
)
}
}
export default Home
Unfortunately, vertical navigation is not supported on Android yet.
I’ve used the react-native-swiper component in a previous project and loved it! I figured I can tweak it a little bit to meet my requirements.
You can clearly see that I have seperated my screens and navigation files in a separate folder.
This is my root navigator file:
import {
createStackNavigator
} from 'react-navigation';
import Login from '../screens/Login';
import SplashScreen from '../screens/SplashScreen';
import HomeNavigation from './HomeNavigation';
export default RootNavigation = createStackNavigator({
// Settings:UserProfile,
SplashScreen: SplashScreen,
Login: Login,
DrawerNavigation: HomeNavigation
}, {
headerMode: 'none',
});
This is my root navigator file:
Here i declare all my screens and link it to the root navigator
import React, {
Component
} from 'react';
import {
Text,
View,
Image,
SafeAreaView,
ScrollView,
Dimensions,
AsyncStorage,
ImageBackground,
TouchableOpacity,
Platform
} from 'react-native';
import {
Icon
} from 'native-base';
import {
createStackNavigator,
createDrawerNavigator,
DrawerItems,
createSwitchNavigator,
Header
} from 'react-navigation';
import AppDataStorage from '../helper/AppDataStorage';
import Colors from '../config/Colors';
import {
RNToasty
} from 'react-native-toasty';
import Home from '../screens/Home';
import Contact from '../screens/Contact';
import AboutUs from '../screens/AboutUs';
import Search from '../screens/Search';
import MyProfile from '../screens/MyProfile';
import {
getStatusBarHeight
} from 'react-native-status-bar-height';
var width = Dimensions.get('window').width;
var height = Dimensions.get('window').height;
var drawerWidth = ((width * 0.75) > 350) ? 350 : (width * 0.75);
const ImageHeader = props => ( <
View style = {
{
backgroundColor: '#eee'
}
} >
<
LinearGradien style = {
{
height: '100%',
width: '100%'
}
}
start = {
{
x: 0,
y: 1
}
}
end = {
{
x: 1,
y: 0
}
}
colors = {
['#4c669f', '#3b5998', '#192f6a']
}
/> <
Header { ...props
}
style = {
{
backgroundColor: 'transparent'
}
}
/> < /
View >
);
const headerOptions = (props) => {
return {
// header: (props) => <ImageHeader {...props} />,
headerStyle: {
backgroundColor: Colors.transparent,
paddingTop: Platform.OS === 'ios' ? 0 : getStatusBarHeight(),
height: Header.HEIGHT + (Platform.OS === 'ios' ? 0 : getStatusBarHeight()),
},
headerTintColor: Colors.white,
headerTitleStyle: {
fontWeight: 'bold',
},
headerMode: 'float',
headerLeft: < Icon
onPress = {
() => props.navigation.openDrawer()
}
name = "menu"
type = 'MaterialIcons'
style = {
{
color: 'white',
marginLeft: 10
}
}
/>,
}
};
class homeDrawerComponent extends Component {
constructor(props) {
super(props);
this.state = {
user: null
};
}
async componentDidMount() {
let user = await AppDataStorage.getUser();
console.log("user drawer", user);
await this.setState({
user: user
});
}
render() {
const email = this.state.user ? this.state.user.email : '';
const name = this.state.user ? (this.state.user.firstName + ' ' + this.state.user.lastName) : '';
return ( <
View style = {
{
flex: 1
}
} >
<
ImageBackground resizeMode = 'cover'
source = {
require('../assets/images/Cover.png')
}
style = {
{
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
height: 200,
marginBottom: 32
}
} >
<
View style = {
{
width: 80,
height: 80,
backgroundColor: Colors.white,
marginTop: 40,
borderRadius: 40
}
} >
<
Image source = {
require('../assets/images/drawer-logo.png')
}
style = {
{
width: 80,
height: 80,
}
}
resizeMode = 'contain' / >
<
/View> <
Text style = {
{
marginTop: 10,
color: Colors.white,
fontSize: 14,
}
} > {
name
} <
/Text> <
Text style = {
{
color: Colors.white,
fontSize: 14,
}
} > {
email
} <
/Text> < /
ImageBackground > <
ScrollView showsVerticalScrollIndicator = {
false
} >
<
DrawerItems activeBackgroundColor = '#1a9eae1a'
activeTintColor = {
Colors.secondaryColor
}
inactiveTintColor = {
Colors.primaryColor
}
labelStyle = {
{
color: Colors.text2
}
} { ...this.props
}
/> <
TouchableOpacity onPress = {
() => {
AsyncStorage.clear();
OneSignal.setSubscription(false);
RNToasty.Info({
title: 'You have been logged out.'
})
this.props.navigation.navigate('SplashScreen');
}
} >
<
View style = {
{
padding: 16,
flexDirection: 'row',
alignItems: 'center'
}
} >
<
Icon
type = "MaterialCommunityIcons"
name = "logout"
style = {
{
fontSize: 24,
color: Colors.primaryColor,
fontWeight: 'bold'
}
}
/> <
Text style = {
{
fontSize: 14,
color: Colors.text2,
fontWeight: 'bold',
marginLeft: 32
}
} > Sign Out < /Text> < /
View > <
/TouchableOpacity> < /
ScrollView > {
/* <TouchableOpacity onPress={() => {
AsyncStorage.clear();
RNToasty.Info({ title: 'You have been logged out.' })
this.props.navigation.navigate('SplashScreen');
}}> */
} {
/* <Icon
onPress={() => {
AsyncStorage.clear();
OneSignal.setSubscription(false);
RNToasty.Info({ title: 'You have been logged out.' })
this.props.navigation.navigate('SplashScreen');
}}
type="MaterialCommunityIcons"
name="logout"
style={{ color: Colors.secondaryColor, padding: 16, textAlign: 'left', marginBottom: 20, fontWeight: 'bold' }}> Logout</Icon> */
} <
/View>
)
}
}
const HomeStack = createStackNavigator({
Home: Home,
Search: Search,
Contact: Contact,
}, {
defaultNavigationOptions: headerOptions
});
HomeStack.navigationOptions = ({
navigation
}) => {
let drawerLockMode = 'unlocked';
if (navigation.state.index > 2) {
drawerLockMode = 'locked-closed';
}
return {
drawerLockMode,
};
};
const AboutUsStack = createStackNavigator({
AboutUs: AboutUs,
}, {
defaultNavigationOptions: headerOptions
});
export default HomeNavigation = createDrawerNavigator({
Home: {
screen: HomeStack,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: ({
tintColor
}) => ( <
Icon type = "FontAwesome5"
name = "home"
style = {
{
fontSize: 20,
color: tintColor
}
}
/>
)
}
},
{
header: null,
contentComponent: homeDrawerComponent,
// drawerWidth
},
);
You're good to go!
Hope this helps.

How to open the camera and taking the picture in react native?

I want to open the device camera from my app when user click on the button and when user click on back button it should react to my application from device camera. I am able to open camera and take photo by running react native project. But I want to do it how camera works in what's app. That is clicking on button -> opening camera -> send button .
I am an beginner in react native .I tried many ways but I am not getting how it can be done.
Can anybody assist me to do this.
My App.js code is,
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
class BadInstagramCloneApp extends Component {
render() {
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => console.log(data))
.catch(err => console.error(err));
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('BadInstagramCloneApp', () => BadInstagramCloneApp);
You can use the state to show/hide the camera view/component.
Please check the following code:
...
class BadInstagramCloneApp extends Component {
constructor(props) {
super(props);
this.state = {
isCameraVisiable: false
}
}
showCameraView = () => {
this.setState({ isCameraVisible: true });
}
render() {
const { isCameraVisible } = this.state;
return (
<View style={styles.container}>
{!isCameraVisible &&<Button title="Show me Camera" onPress={this.showCameraView} />}
{isCameraVisible &&
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>}
</View>
);
}
takePicture() {
const options = {};
//options.location = ...
this.camera.capture({metadata: options})
.then((data) => {
console.log(data);
this.setState({ isCameraVisible: false });
}
.catch(err => console.error(err));
}
}
...
You can use https://github.com/ivpusic/react-native-image-crop-picker for this. This component helps you to take photo and also the photo if required. Follow the documentation correctly and here is the code for camera selection option
ImagePicker.openCamera({
cropping: true,
width: 500,
height: 500,
cropperCircleOverlay: true,
compressImageMaxWidth: 640,
compressImageMaxHeight: 480,
freeStyleCropEnabled: true,
}).then(image => {
this.setState({imageModalVisible: false})
})
.catch(e => {
console.log(e), this.setState({imageModalVisible: false})
});
Correction of best answer because of deprecation of Camera to RNCamera plus missing closing bracket ")" right before the .catch and like a spelling mistake with the declaration of state:
But basically there's 2 routes, whether you're using expo or react native. You gotta have Pods/Ruby/Cocoapods or manually link and all that if you're using traditional React Native, but just go with expo-camera if you got an expo set up and don't listen to this.
This is a React-Native with Pods/Ruby/CocoaPods solution, whereas going with expo-camera might be much faster and better if you're not set up like this.
import React, { Component } from 'react';
import {
Text,
View,
StyleSheet,
Button,
TouchableOpacity
} from 'react-native';
import { RNCamera } from 'react-native-camera';
export default class Camera2 extends Component {
constructor(props) {
super(props);
this.state = {
isCameraVisible: false
}
}
showCameraView = () => {
this.setState({ isCameraVisible: true });
}
takePicture = async () => {
try {
const data = await this.camera.takePictureAsync();
console.log('Path to image: ' + data.uri);
} catch (err) {
// console.log('err: ', err);
}
};
render() {
const { isCameraVisible } = this.state;
return (
<View style={styles.container}>
{!isCameraVisible &&<Button title="Show me Camera" onPress={this.showCameraView} />}
{isCameraVisible &&
<RNCamera
ref={cam => {
this.camera = cam;
}}
style={styles.preview}
>
<View style={styles.captureContainer}>
<TouchableOpacity style={styles.capture} onPress={this.takePicture}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
<Text>Take Photo</Text>
</TouchableOpacity>
</View>
</RNCamera>}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});

Change underlineColorAndroid on Focus for TextInput in react-native

Similar to Focus style for TextInput in react-native, I am trying to change the property underlineColorAndroid for the textInput.
I am using React-Native 0.28.0
OnFocus, the attribute doesn't change. How do I change the underline to a different color onFocus?
My sample code is below:
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
ScrollView
} from 'react-native';
class RNPlayground extends Component {
constructor(props) {
super(props);
this.state = {
hasFocus: false
}
}
_onBlur() {
this.setState({hasFocus: false});
}
_onFocus() {
this.setState({hasFocus: true});
}
_getULColor(hasFocus) {
console.error(hasFocus);
return (hasFocus === true) ? 'pink' : 'violet';
}
render() {
console.error("this.state=");
console.error(this.state);
console.error("this.state.hasFocus=");
console.error(this.state.hasFocus);
return (
<View style={styles.container}>
<ScrollView>
<TextInput
placeholder="textInput"
onBlur={ () => this._onBlur() }
onFocus={ () => this._onFocus() }
style={styles.instructions}
underlineColorAndroid={this._getULColor(this.state.hasFocus)}/>
</ScrollView>
<TextInput>Some sample text</TextInput>
</View>
);
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 28,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
fontSize: 19,
marginBottom: 5,
}
});
AppRegistry.registerComponent('RNPlayground', () => RNPlayground);
Well, your code is correct and it should work properly.
Here is working example
Please, stop downvote this answer. Unfortunately rnplay service isn’t available anymore, as like this example. Or downvote but explain your point.