Unable to perform onPress in ReactNative nested component - react-native

So I am using react native and an unable to get the function to be called onPress. I have a SearchUser component which has a render method within which I have called
<ShowUsers allUsers={this.state.details} access_token={this.state.access_token}/>
Now the ShowUsers is as follows
class ShowUsers extends Component{
....
render(){
var user = this.state.details;
var userList = user.map(function(user,index){
var img={
uri:user.avatar.uri,
}
return(
<ListItem icon key={ index }>
<Left>
<Thumbnail small source={img} />
</Left>
<Body>
<Text>{"#"+user.uname+" "+user.id}</Text>
<Text note>{user.fname+" "+user.lname}</Text>
</Body>
<Right>
<Icon style={{fontSize:30}} name="ios-add-circle" onPress={this.followThem(user.id).bind(this)} />
</Right>
</ListItem>
);
});
return(
<View>
{userList}
</View>);
}
followThem(userId){
Alert.alert("userId "+userId);
}
When I click the icon I get the following errror
undefined is not a function (evaluating this.followThem(user.id))
As far as I understand the value of this is undefined however I have used functions such as the one below in my SearchUser component. Which calls the function properly
<Icon onPress={this.goBack.bind(this)} name="arrow-back" />
I have also tried this.followThem.bind(this,user.id) but to no avail what am I doing wrong?

A simplified answer -
render() {
var user = [11,22,33];
var userList = user.map((u,i) => {
return(
<Text key={i} onPress={this.followThem.bind(this, u)}>{u}</Text>
);
});
.....
}
Notice the arrow function used in map. It automatically binds this to callback.
You can also do -
<Text key={i} onPress={() => this.followThem(u)}>{u}</Text>

Related

How to call parent's function in react native?

How to call the parent's function in the child component?
I followed this answer, but it doesn't work for me. How to solve this?
React native how to call functions of parent class
This is my code.
Parent
<View>
<HeaderHome onClick={this.openDrawer} />
</View>
openDrawer() {
alert('I am clicked.')
}
Child component
<TouchableOpacity onPress={this.props.bind(this.props.onClick)} >
<Image source={url} />
</TouchableOpacity>
Take it a try:
Parent
<View>
<HeaderHome onClick={this.openDrawer} />
</View>
openDrawer = () => {
alert('I am clicked.')
}
Children
<TouchableOpacity onPress={() => { this.props.onClick()}} >
<Image source={url} />
</TouchableOpacity>

FlatList's renderItem doesn't recognise "this" keyword

So, I recently started making FlatList a recurring thing in the app I'm working on. I am right now working on a screen that gives a list of requests and is updated once one is accepted, which is done by pressing a button. There's a method called getNewRequests I am using to update the requests, but it can't seem to be called by the flatline, as it only returns the error TypeError: _this3 is undefined.
I really need that method to work, because I need to update the state of that screen, and trying to type the whole method there only returns the same error. In that context, this always returns undefined.
render(){
return(
<View style={GenericStyles.styles.genericContainer}>
<Text> REQUEST SCREEN </Text>
<FlatList
data={this.state.requestList}
renderItem={this.renderItem}
keyExtractor={item => item.id}
/>
<Button title="Voltar" color="cyan" onPress={() => this.props.navigation.goBack()}/>
</View>
);
}
renderItem({item}){
return(
<Card
containerStyle={{flex: 1, width: 200}}
title={item.Username}>
<Button color="blue" title="Accept" onPress={() => RequestService.allowRequest(item.id, (response) => {
let rsp = JSON.parse(response);
if(rsp.success){
this.getNewRequests();
}
})}/>
</Card>
);
}
You need to either bind the function in your constructor (or wherever you want) doing:
constructor(props){
super(props)
this.renderItem.bind(this)
}
or use arrow function:
renderItem = ({item}) => {
//your function
}
Doing this will give the function access to the this of the current component.

React Native - Function doesn't seem to be called

I have a simple app with 2 images. When I click on image1, I want to display hello on the console.
But my function doesn't write anything in the console.
I didn't use a function and called directly console.log in the 2nd image and it works.
Do you know what is wrong with my function?
(I also used makeALogHello.bind(this) but it doesn't change the behavior).
export default class App extends React.Component {
constructor(){
super();
}
makeALogHello(){
console.log("hello");
}
render() {
return (
<View>
<TouchableOpacity style ={{flex:1}}
onPress={() => {this.makeALogHello} }>
<Image style ={styles.container}
resizeMode="contain"
source={require("./images/image1.png")}/>
<Text>ImageNb1</Text>
</TouchableOpacity>
<TouchableOpacity style ={{flex:1}}
onPress={() => {console.log("hi")} }>
<Image style ={styles.container}
resizeMode="contain"
source={require("./images/image2.png")}/>
<Text>ImageNb2</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
You need to call the function in your arrow function:
onPress={() => {this.makeALogHello()} }
Or simply pass the reference to your function, without wrapping it:
onPress={this.makeALogHello}

React native onPress with TouchableWithoutFeedback is not working

I am developing a simple React Native application for learning purpose. I am just taking my initial step to get into the React Native world. But in this very early stage, I am having problems. I cannot get a simple touch event working. I am implementing touch event using TouchableWithoutFeedback. This is my code.
class AlbumList extends React.Component {
constructor(props)
{
super(props)
this.state = {
displayList : true
}
}
componentWillMount() {
this.props.fetchAlbums();
}
albumPressed(album)
{
console.log("Touch event triggered")
}
renderAlbumItem = ({item: album}) => {
return (
<TouchableWithoutFeedback onPress={this.albumPressed.bind(this)}>
<Card>
<CardSection>
<Text>{album.artist}</Text>
</CardSection>
<CardSection>
<Text>{album.title}</Text>
</CardSection>
</Card>
</TouchableWithoutFeedback>
)
}
render() {
let list;
if (this.state.displayList) {
list = <FlatList
data={this.props.albums}
renderItem={this.renderAlbumItem}
keyExtractor={(album) => album.title}
/>
}
return (
list
)
}
}
const mapStateToProps = state => {
return state.albumList;
}
const mapDispatchToProps = (dispatch, ownProps) => {
return bindActionCreators({
fetchAlbums : AlbumListActions.fetchAlbums
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(AlbumList);
As you can see, I am implementing touch event on the list item. But it is not triggering at all when I click on the card on Simulator. Why? How can I fix it?
You should wrap your content in component like this:
<TouchableWithoutFeedback>
<View>
<Your components...>
</View>
</TouchableWithoutFeedback>
TouchableWithoutFeedback always needs to have child View component. So a component that composes a View isn't enough.
So instead of
<TouchableWithoutFeedback onPressIn={...} onPressOut={...} onPress={...}>
<MyCustomComponent />
</TouchableWithoutFeedback>
use:
<TouchableWithoutFeedback onPressIn={...} onPressOut={...} onPress={...}>
<View>
<MyCustomComponent />
</View>
</TouchableWithoutFeedback>
See the github issue for more info
Can be used with <TouchableOpacity activeOpacity={1.0}> </TouchableOpacity>
For those who struggle with this issue in react-native 0.64, and wrapping it in just a View doesn't work, try this:
<TouchableWithoutFeedback onPress={onPress}>
<View pointerEvents="none">
<Text>Text</Text>
</View>
</TouchableWithoutFeedback>
In my case i accidentally imported TouchableWithoutFeedback from react-native-web instead of react-native. After importing from react-native everything worked as expected.
In more recent React Native versions, just use Pressable instead:
https://reactnative.dev/docs/pressable
In my case, there was a shadow underneath, which caused instability. What I did to solve it was quite simple: zIndex: 65000
<View style={{ zIndex: 65000 }}>
<TouchableWithoutFeedback onPressIn={() => {}>
<View>
</View>
</TouchableWithoutFeedback>
</View>

passing a variable and a function using props in react native

I am passing a variable and a function using props in react native.
<ModalHeader message={'Мои заказы'}
onPress={() => {
goBack();
}} />
In HeaderModel.js
static propTypes = {
onPress: PropTypes.func.isRequired,
message: PropTypes.string
};
render() {
return (
<Header style={styles.header}>
<Left>
<Button rounded transparent onPress={ this.props.onPress }>
<Icon name='arrow-back'/>
</Button>
</Left>
<Body>
{ this.props.message }
</Body>
</Header>
);
}
When I run app, "app is not responding" error appears. What is wrong with my code? Any solutions ?
Just change your ModalHeader to this:
<ModalHeader message={'Мои заказы'} onPress={this.goBack} />
This will pass the goBack function to ModalHeader Class