How to call parent's function in react native? - 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>

Related

React native Flatlist inside modal does not show data sometime

I am trying to to data using Flatlist inside a Modal. But sometimes (Not always) data is not displayed at all. Just empty screen. I am using expo client for test. Below is my code. This render() method is actually in a custom component. So, Modal is inside a custom component. I am not sure Modal has to cause any issue here.
// sometime flatlist does not work when inside a modal
render(){
return (
<View>
{ this.props.visible && this.renderChildModal()}
{ this.props.visible &&
<Modal
animationType="slide"
transparent={false}
visible={true}
onRequestClose={() => {
//Alert.alert('Modal has been closed.');
}}>
<View>
<View style={this.styles.buttonContainer}>
<TouchableOpacity style={this.styles.button}
onPress={this.props.onDone}>
<Text style={styles.labelButton}>Done</Text>
</TouchableOpacity>
</View>
<FlatList
data={this.state.items}
extraData ={this.state}
renderItem={({ item }) => (
<CheckBox
title={item.name}
checked={item.checked}
onPress={()=>this.onSelect(item.id-1)}
/>
)}
keyExtractor={item => item.id.toString()}
/>
</View>
</Modal>
}
</View>
)
}
It was not a problem with Modal. I was calling component named MultiSelect in screen as below,
<MultiSelect
items={specialities}
selectedItems={profile.specialities}
onItemSelected={this.onSelectedSpecialitiesChange}
visible={this.state.specialitiesModalVisible}
onDone={this.specialityMultiSelectDone}
>
</MultiSelect>
Sometime specialities is empty as it is retrieved from server asynchronously.
So, I changed my code as below,
{specialities.length>0 &&
<MultiSelect
items={specialities}
selectedItems={profile.specialities}
onItemSelected={this.onSelectedSpecialitiesChange}
visible={this.state.specialitiesModalVisible}
onDone={this.specialityMultiSelectDone}
>
</MultiSelect> }
That solves the issue.

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>

how to navigate from nested component to other component react native?

i have a component in which on button click i render a component
<View style={styles.container}>
<Text> in Default component!</Text>
<Button title="add"
onPress={this.handelSubmit} />
{items.map((item, index) => (
<Home key={index} data={index} />))}
</View>
and my home component look like
<View style={styles.container}>
<Text onPress={() => { this.props.navigation.navigate("Calculator")}}>Semester {this.props.data +1}</Text>
</View>
onPress event i want to navigate to other screen i.e 'Calculator.js' but i got an error
i am using react-navigation for navgation
If you want to navigate from a component, you have to use your component like this:
<Home key={index} data={index} navigation={this.props.navigation} />

React Native: can't call a parent method from child

I have this function in parent component, and I am trying to call this method/function in child , like so:
buttonPressed = () => {
console.log('button pressed')
}
<childComp ref={ref => this.feedback = ref}
onPress={this.buttonPressed}
/>
in child:
<Animated.View>
... // other views
<View>
<TouchableOpacity onPress={this.props.buttonPressed}> // calling here
...
</TouchableOpacity>
</View>
</Animated.View>
No matter what I tried , it didn't work.
you are passing onPress prop to child and calling buttonPressed in child. it should be like this :
<Animated.View>
... // other views
<View>
<TouchableOpacity onPress={this.props.onPress}> // calling here
...
</TouchableOpacity>
</View>
</Animated.View>
I think that in child component you should call to this.props.onPress(), because the name of the property thar you are passing is onPress. Also, don't forget to put () when you want to call the function. So it should be:
<Animated.View>
... // other views
<View>
<TouchableOpacity onPress={this.props.onPress()}> // calling here
...
</TouchableOpacity>
</View>
</Animated.View>

Unable to perform onPress in ReactNative nested component

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>