this.refs returning undefined value - android

I am new to react-native as well as to android, upon clicking of button, I get an undefined response when I try to access values referenced in TextInput
Upon looking on previous solution, I tried binding my log in button and still the problem was not solved
function login(event)
{
var email = this.refs.email;
var password = this.refs.password;
console.log(email + ": " + password); // gives undefined: undefined
}
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Image source={require('./logo.png')} />
<Text style={styles.welcome}>Login</Text>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 300}}
placeholder={'E-mail'}
ref = {this.email}
onChangeText={(text) => this.setState({text})}
/>
<Text>{"\n"}</Text>
<TextInput secureTextEntry={true}
style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 300}}
placeholder={'Password'}
ref = {this.password}
onChangeText={(text) => this.setState({text})}
/>
<Text>{"\n"}</Text>
<Button
title="Log In"
onPress={login.bind(this)}
/>
</View>
);
}
}

Usage of this.refs is deprecated.
Work with refs as function. For example:
export default class App extends Component {
let viewRef = null;
render() {
return (
<View ref={ref => (this.viewRef = ref)}>
<Button
title="Log In"
onPress={() => console.log(this.viewRef)}
/>
</View>
)
}
}

Related

How to get photo id with onPress function?

I need to open touched photo in new screen or modal window, but i can't even get it id with onPress function. Photos parsed from unsplash.com.
I've try to wrap my view with <TouchableWithoutFeedback> and by using onPress{} recieve id of photo that i'm pressed at.
getPhoto function:
_getPhoto = () => {
alert(this.state.item.id);
}
main view:
<TouchableWithoutFeedback onPress={this._getPhoto}>
<View style={styles.MainContainer}>
<FlatList
data={ this.state.dataSource }
numColumns={2}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) =>
<View style={{flex:1, flexDirection: 'column'}}>
<Image source = {{ uri: item.urls.raw }} style={styles.imageView} />
</View>
}
keyExtractor={(item, index) => index.toString()}
extraData={this.state}
/>
</View>
</TouchableWithoutFeedback>
I except to recieve at least photo id from json, but most of all i get errors like "undefined is not an object".
I solved this problem doing this:
renderItem={({item}) =>
<TouchableWithoutFeedback onPress = {this._getPhoto.bind(item.id)}>
<View style={{flex:1, flexDirection: 'column'}}>
<Image source = {{ uri: item.urls.raw }} style={styles.imageView} />
</View>
</TouchableWithoutFeedback>
}
but now onPress works on app launch.
The answer was in binding.I'm bind item.id to get function:
renderItem={({item}) =>
<TouchableWithoutFeedback onPress = {this._getPhoto.bind(item.id)}>
<View style={{flex:1, flexDirection: 'column'}}>
<Image source = {{ uri: item.urls.raw }} style={styles.imageView}
</View>
</TouchableWithoutFeedback>
}
And change content of _getPhoto to this:
_getPhoto(){
alert(this);
}
So it's works like it does.

react native camera wont work on second invokation

React native camera won't work on second invokation in Android. On the second invokation the app crashes.
I am using
react-native: 0.56.0
react-native-camera: 1.6.4
It's the same when I use latest version of the react-native-camera.
I can't update react-native to the latest because I have another package that is not compatible with the latest one and It's work fine on the emulator, only problem with real devices
The --scan result is
My camera screen
class CameraScreen extends Component {
constructor(props) {
super(props);
this.state = {
boltIconIsPressed: false,
};
}
renderError() {
Alert.alert(
'Error',
'Something went wrong, Try again!',
[
{ text: 'Ok', style: 'cancel' },
],
);
this.props.navigation.goBack();
}
render() {
if (this.props.isFocused) {
return (
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
style={styles.preview}
type={RNCamera.Constants.Type.back}
flashMode={this.state.boltIconIsPressed ? RNCamera.Constants.FlashMode.off : RNCamera.Constants.FlashMode.on}
onMountError={this.renderError.bind(this)}
permissionDialogTitle={'Permission to use camera'}
permissionDialogMessage={'We need your permission to use your camera phone'}
/>
<View
style={{ flex: 0,
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: 'transparent' }}
>
<Button
outline
rounded
style={styles.capture}
onPress={() => this.props.navigation.navigate('gallery')}
>
<Icon
type='Entypo'
name='image'
style={{ color: '#862d59', }}
/>
</Button>
<Button
outline
rounded
onPress={this.takePicture.bind(this)}
style={styles.capture}
>
<Icon
type='SimpleLineIcons'
name='camera'
style={{ color: '#862d59', }}
/>
</Button>
<Button
outline
rounded
style={styles.capture}
onPress={() => this.setState({ boltIconIsPressed:
!this.state.boltIconIsPressed })}
>
<Icon
type='MaterialCommunityIcons'
name={this.state.boltIconIsPressed ? "flash-off" : "flash"}
style={{ color: '#862d59', }}
/>
</Button>
</View>
</View>
);
}
return (
<View />
);
}
takePicture = async function () {
let data = null;
if (this.camera) {
const options = {
width: 1800,
base64: true,
};
console.log(data);
data = await this.camera.takePictureAsync(options);
this.props.navigation.navigate('uploadscreen', {
image: data,
});
}
};
}
export default withNavigationFocus(CameraScreen);
Thanks in advance
I got this error because I doesnot have the storage to save the taken image. To make it work, add this in AndroidManifest.xml file
android:largeHeap="true"

Click event on words react native

I want to set different click listeners on different words of . Currently what i have is
<Text>Android iOS React Native<Text>
Now i want to know when user click on Android, iOS and React Native, i have to perform some analytics on that so need click listeners for seperate words.
Does any one have idea about it? I have checked this thread but i din't found it useful for my requirement.
Update
String i have given is just an example string, in real time i will be getting dynamic strings.
This is what i will be getting as dynamic string
{
"str":"Hi i am using React-Native, Earlier i was using Android and so on"
"tagWords":["React-Native","Android"]
}
And in output i want, "Hi i am using React-Native, Earlier i was using Android and so on"
with click event on "React-Native" and "Android". Is is possible?
The post you sent is the simplest way you can achieve the desired behavior. Sinse you need to have different listeners you need to implement different Text components.
Example
export default class App extends Component {
onTextPress(event, text) {
console.log(text);
}
render() {
return (
<View style={styles.container}>
<Text>
<Text onPress={(e) => this.onTextPress(e, 'Android')} style={styles.red}>{'Android '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'iOS')} style={styles.purple}>{'iOS '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'React Native')} style={styles.green}>{'React Native'}</Text>
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
red: {
fontSize: 20,
color: 'red'
},
purple: {
fontSize: 20,
color: 'purple'
},
green: {
fontSize: 20,
color: 'green'
}
});
Update 1 (Dynamic text)
render() {
const fixedString = 'I\'m a fixed string that slipleted';
const arrayOfStrings = ['These', 'are', 'strings', 'from', 'array'];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
fixedString.split(' ').map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (fixedString.split(' ').lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
<Text style={styles.textContainer}>
{
arrayOfStrings.map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (arrayOfStrings.lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
</View>
);
}
Update 2 (for example dynamic data)
removePunctuation = (text) => {
// this is a hack to remove comma from the text
// you may want to handle this different
return text.replace(/[.,\/#!$%\^&\*;:{}=\_`~()]/g,"");
}
render() {
const arrayOfObjects = [{
str: 'Hi i am using React-Native, Earlier i was using Android and so on',
tagWords: ['React-Native', 'Android']
}];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
arrayOfObjects.map((obj) => {
return obj.str.split(' ').map((s, index) => {
if ( obj.tagWords.indexOf(this.removePunctuation(s)) > -1 ) {
return (
<Text onPress={(e) => this.onTextPress(e, s)} style={styles.red}>
{`${s} ${index !== (obj.str.split(' ').lenght - 1) && ' '}`}
</Text>
)
} else return `${s} `;
})
})
}
</Text>
</View>
);
}
all you need to use is TouchableOpacity(for the tap effect and clicks), View for the alignment of texts. and certain styling. I am providing you the code snippet that will work for you , all other syntax will remain same
import {Text, View, TouchableOpacity} from 'react-native'
<View style={{flexDirection:'row'}}>
<TouchableOpacity onPress={{()=>doSomethingAndroid()}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={{()=>doSomethingiOS()}}><Text> iOS</Text>
</TouchableOpacity>
<TouchableOpacityonPress={{()=>doSomethingReactNative()}}><Text> React Native</Text>
</TouchableOpacity>
</View>
i hope this works, comment back if any issue happens
You can wrap each clickable words into 'TouchableOpacity' component, and tract the onPress event as follows
<View style={{flexDirection: 'row'}}>
<TouchableOpacity onPress={() => {
console.log('Android Clicked');
}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {
console.log('iOS Clicked');
}}>
<Text>Ios</Text>
</TouchableOpacity>
</View>
Please do adjust the spacing between words.
Edit:
For dynamic string you can proceed as follows
...
handleWordClick(str, handler) {
var words = str.split(' '), // word separator goes here,
comp = [];
words.forEach((s, ind) =>{
comp.push(
<TouchableOpacity key={ind} onPress={() => handler.call(this, s)}>
<Text>{s}</Text>
</TouchableOpacity>
);
})
return comp;
}
render() {
var comp = this.handleWordClick('Android iOS React-Native', (word) => {
//handle analytics here...
console.log(word);
});
return (
<View>
...
<View style={{flexDirection: 'row'}}>
{comp}
</View>
...
</View>
)
}
I am not sure what will be your word separator as the example you have given has 'React Native' as single word. Please pay attention on this part.
Hope this will help you.

How focus the next field input in react native?

I need focus the next field input in react native, in android platform.
But the focus() function, not exists in android react native, only in IOS.
How make this ? I use react native with typescript.
The focus function works just fine.
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Name: </Text>
<TextInput ref="name" onChangeText={(name) => this.setState({name})} style={{flex: 1}}
onSubmitEditing={() => this.refs.age.focus()}/>
</View>
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Age: </Text>
<TextInput ref="age" keyboardType="numeric" onChangeText={(age) => this.setState({age})} style={{flex: 1}}
onSubmitEditing={() => this.refs.sport.focus()}/>
</View>
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Favourite Sport: </Text>
<TextInput ref="sport" onChangeText={(sport) => this.setState({sport})} style={{flex: 1}}/>
</View>
Hope this helps. This is for android.
You have to user ref on Inputs where you want to focus on:
<Input
ref={(node) => { this.myInput = node }}
value={this.state.myInput.toString()}
onSubmitEditing={() => { this.myOtherInput.focus() }}/>
<Input
ref={(node) => { this.myOtherInput = node }}
value={this.state.myOtherInput.toString()}/>
You can see that when you submit the editing on the first input you will focus on the second one. you can use this.MY_CUSTOM_REF.focus() wherever you want.
This work for me:
<Input
blurOnSubmit={false}
returnKeyType="next"
onSubmitEditing={() => {
this.passwordInput.wrappedInstance.focus();
}}
/>
<Input
secureTextEntry
ref={(input) => {
this.passwordInput = input;
}}
/>
I insert the function in my customize component.
public focus(){
this.input.focus()
}
Have a look at this article, this might be handy react-native inputs
//Helper function
focusNextField(nextField) {
this.refs[nextField].focus();
}
<TextInput
ref='1'
style={styles.otpInputStyle}
keyboardType='numeric'
secureTextEntry
value={this.props.otp1}
maxLength={1}
onChangeText={(num) => {
this.props.otpCode1(num); //action call
if (num && num.length === 1) {
this.focusNextField('2'); //function call. '2' ref to next input ref
}
}}
/>
import React, { useRef } from 'react';
...
export default function YourFuctionalComponent() {
const input1 = useRef(null);
const imput2 = useRef(null);
const doSomething = () => {}
return(
<>
<TextInput
autoFocus
ref={input1}
onSubmitEditing={() => { imput2.current.focus(); }}
returnKeyType="next"
/>
<TextInput
ref={input2}
onSubmitEditing={() => doSomething()}
returnKeyType="done"
/>
</>
);
}
https://i.stack.imgur.com/W6dvs.gif

react-native android LinkingIOS

Error undefined is not an object(evaluating 'RCTLinkingManager,openURL')
The documentation says LinkingIOS is being deprecated. Use Linking instead. Yet there is nothing else about that and all references are to LinkingIOS
var {Image, View, Text, ScrollView, BackAndroid, StyleSheet, LinkingIOS} = React;
render: function() {
var url = 'http://google.com';
return (
<View style={property.color}>
<Image source={require('../img/glow2.png')} style={property.container}>
<Navbar
title="Property Info"
subtitle=""
style={property.toolbar}
subtitleStyle={property.subtitle} />
<ScrollView style={{marginBottom: 55, backgroundColor: 'transparent'}}>
<View style={property.propertyContent}>
<Icon name="android-checkbox-outline" size={20} color="rgba(255,255,255,0.9)" style={{position: 'absolute',top:0, left: 0}}/>
<Text style={property.content}>url {url} </Text>
<Text style={{color: 'yellow'}}
onPress={() => LinkingIOS.openURL(url)}>
Google</Text>
</ScrollView>
</Image>
</View>
);
}
NOTE: LinkingIOS is being deprecated. Use Linking instead.
This means you should be using Linking as a reference in your code rather than LinkingIOS.

Categories

Resources