How to get photo id with onPress function? - android

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.

Related

how to call this add function

I am using andSubject function to set the subject in the parent component but it's not working can someone help me how can I call addSubject when I press the RoundedButton?
...
const [tempItem, setTempItem] = useState(null);
.....
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
onSubmitEditing={({ nativeEvent }) => {
setTempItem(nativeEvent.text);
// addSubject(nativeEvent.text);
}}
/>
<RoundedButton
title="+"
size={50}
onPress={() => addSubject(tempItem)}
/>
</View>
...
I guess you are looking for something like this :
const [tempItem, setTempItem] = React.useState("");
const [addSubject , setAddSubject] = React.useState("");
...
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<Text>this text bellow will show after pressing on the button :</Text>
<Text>{addSubject}</Text>
<TextInput
style={styles.textInput}
onChangeText={setTempItem}
/>
<Button
title="+"
size={50}
onPress={() => setAddSubject(tempItem)}
/>
</View>
</View>
);
}
...
demo
You have to pass the function to children by props.
parent.js
function setAddSubject(item){
console.log(item)
}
<YourForm call={(item)=>setAddSubject(item) } />
YourForm.js
export default =(props)=>{
const [tempItem, setTempItem] = useState(null);
return (
<View style={styles.inputContainer}>
<TextInput
style={styles.textInput}
onSubmitEditing={({ nativeEvent }) => {
setTempItem(nativeEvent.text);
// addSubject(nativeEvent.text);
}}
/>
<RoundedButton
title="+"
size={50}
onPress={() => props.call(tempItem)}
/>
</View>
);
}

React native onStartShouldSetResponder parameter not working for AutoCompeletInput plugin

I am using plugin for Autocomplete Input. I have placed this component in Scrollview. It's other behaviour is fine like displaying suggestion list in popup with our custom design.
Referred Plugin:- Plugin
But onStartShouldSetResponder{()=>true} not working.
Because of that I am unable to scroll my suggestion list.
Here is my implemented code =>
<ScrollView keyboardShouldPersistTaps='always' style={[commonstyles.mainContainer,styles.mainContainer,{marginBottom:20}]}>
<View style={{width:width-30,height:45}}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
hideResults={false}
containerStyle={{flex: 1,left: 10,position: 'absolute',right: 10,top: 0,zIndex: 1}}
data={films.length === 1 && comp(query, films[0].name) ? [] : films}
defaultValue={query}
onChangeText={text => this.setState({ query: text })}
placeholder="Select Contact"
renderItem={({ id,name }) => (
<TouchableOpacity onStartShouldSetResponder={()=>{return true;}} activeOpacity={1} onPress={() => this.setState({ query: name })}>
<Text style={{fontSize:Global.DESCRIPTION_FONT_SIZE,color:Global.APP_BLACK_COLOR,borderBottomWidth:0.5,borderColor:Global.APP_BLACK_COLOR,padding:5}}>
{id} {name}
</Text>
</TouchableOpacity>
)}
/>
</View>
</Scrollview>
Please let me know if I am doing something wrong.
Also I am unable to understand implementation of onStartShouldSetResponder() function.
Suggest Autocomplete input example in react native which work like Android AutoCompleteTexview component.
Add scrollEnabled parameter to your Scrollview.
Try with below code
<ScrollView scrollEnabled={this.state.enableScrollViewScroll} keyboardShouldPersistTaps='always' style={[commonstyles.mainContainer,styles.mainContainer,{marginBottom:20}]}>
<View style={{width:width-30,height:45}}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
hideResults={false}
onStartShouldSetResponderCapture={() => {
var self=this;
this.setState({ enableScrollViewScroll: false });
console.log("Here==>",self.state.enableScrollViewScroll);
}}
containerStyle={{flex: 1,left: 10,position: 'absolute',right: 10,top: 0,zIndex: 1}}
data={films.length === 1 && comp(query, films[0].name) ? [] : films}
defaultValue={query}
onChangeText={text => this.setState({ query: text })}
placeholder="Select Contact"
renderItem={({ id,name }) => (
<TouchableOpacity activeOpacity={1} onPress={() => this.setState({ query: name,enableScrollViewScroll:true })}>
<Text style= {{fontSize:Global.DESCRIPTION_FONT_SIZE,color:Global.APP_BLACK_COLOR,borderBottomWidth:0.5,borderColor:Global.APP_BLACK_COLOR,padding:5}}>
{id} {name}
</Text>
</TouchableOpacity>
)}
/>
</View>
</Scrollview>

Creating a GridView From Listview in ReactNative?(Without using libraries)

Consider a simple app in React Native that fetches listings from a remote JSON source and displays them on screen.
So far,I've managed to get the results to display using the ListView components in rows (i.e. 2 result per row, see screenshot).
in one row.both the grids display data of a single person,i want
details in a consecutive manner not repeating.
</Content>
<View style={{backgroundColor: 'white'}}>
<Text style={{color: 'black',fontSize: 17,marginTop: 25,marginLeft: 15}}>Employees</Text>
</View>
<List dataArray={currentContext.props.employeeList}
renderRow={(data) =>
<ListItem>
{this.renderRow(data)}
</ListItem>
} />
</Content>
The function renderRow(data) is given by
renderRow(data){
return(
typeOne()
)
function typeOne(){
return(
<View style={styles.gridContainer}>
<Content contentContainerStyle={{
padding:6,
paddingBottom:0
}}>
<View style={{flex:1,}}>
<Row>
{renderCell(data.photo_url, 0,data.name)}
{renderCell(data.photo_url, 1,data.name)}
</Row>
</View>
</Content>
</View>
)
function renderCell(bg,pos,title){
if (pos%2==0) {
return(
<Col style={[{marginRight:3},styles.colStyle]}>
{cellContent(bg,title)}
</Col>
)
}else{
return(
<Col style={[{marginLeft:3},styles.colStyle]}>
{cellContent(bg,title)}
</Col>
)
}
function cellContent(bg,title){
if(bg==null){
return null
}
return(
<Button style={{flex:1,alignSelf:'stretch'}} underLayouColor='red'>
<View style={styles.cellContent}>
<Image style={{height:230,alignItems: 'stretch'}} source={{uri:bg}} blurRadius={1}/>
<View style={[styles.cellTitleBg,{opacity: 0.5,marginTop: 10}]}>
<Text style={[styles.cellTitle,{position:'absolute',bottom:0,right:5}]}>{title}</Text>
</View>
</View>
</Button>
)
}
}
}
}
How can get the list-view to return 2 data's per row ?
I will give you similar question for reference in the below link
ListView grid in React Native
please help me solve this issue.
The style part
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor:'white',
},
button:{
color:'white'
},
overLayView: {
position:'absolute',
alignSelf:'center',
},
gridContainer: {backgroundColor:'#EDF0F2',flex:1,},
colStyle:{height:210,flex:1,marginBottom:6,marginRight:10,marginLeft:10},
cellContent:{position:'absolute',left:0,right:0,top:0,bottom:0},
cellTitleBg:{bottom:65,backgroundColor:'#778899',height:35},
cellTitle:{bottom:65,color:'white',fontWeight:'bold',fontSize:17,right:0,textAlign:'right',right:0}
})
Maybe use a wrapper library, I recommend this one: https://www.npmjs.com/package/react-native-easy-listview-gridview
Try this out...
pass index from the renderRow function down to this function where this view is defined.
<Button key={index} style={{flex:1,alignSelf:'stretch'}} underLayouColor='red'>
<View key={index} style={styles.cellContent}>
<Image key={index} style={{height:230,alignItems: 'stretch'}} source={{uri:bg}} blurRadius={1}/>
<View key={index} style={[styles.cellTitleBg,{opacity: 0.5,marginTop: 10}]}>
<Text key={index} style={[styles.cellTitle,{position:'absolute',bottom:0,right:5}]}>{title}</Text>
</View>
</View>
</Button>

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 error :undefined is not a function (evaluating 'this._pressRow()')

some code:
renderMovie(product) {
<TouchableHighlight
onPress={this._pressRow()}>
<View style={styles.container}>
<View style={styles.rightContainer}>
<Text style={styles.title}>{product.brand_domain}</Text>
<Text style={styles.year}>{product.product_name}</Text>
</View>
</View>
</TouchableHighlight>
}
_pressRow(){
this.props.navigator.push({
title:'detail',
component:DetailView
})
}
1.red screen and error log :undefined is not a function (evaluating 'this._pressRow()')
2.I use 'this._pressRow = this._pressRow.bind(this);' in constructor()
but its not work
3.doc example.but if I use 'onPress={this._onPressButton}' ,Click event no effect
renderButton: function() {
return (
<TouchableHighlight onPress={this._onPressButton}>
<Image
style={styles.button}
source={require('image!myButton')}
/>
</TouchableHighlight>
);
},
You have a scope problem here..
To fix it there are two possible solutions :
You need to bind this to the method :
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie.bind(this)}
/>
You can use ES6 fat arrows
renderMovie = (product) => {
<TouchableHighlight
onPress={this._pressRow()}>
<View style={styles.container}>
<View style={styles.rightContainer}>
<Text style={styles.title}>{product.brand_domain}</Text>
<Text style={styles.year}>{product.product_name}</Text>
</View>
</View>
</TouchableHighlight>
}
and the _pressRow method :
_pressRow(){
this.props.navigator.push({
title:'detail',
component:DetailView
})
}
When you declare your renderRow function in your ListView, you should bind this to the method:
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie.bind(this)}
/>

Categories

Resources