Passing a value via props onPress - javascript

I know we can call the function like {this.props.onPress}, can we pass value using this callback too? Default object is passed but I want to pass a string value using this function. Is this possible, I'm posting my code to clear the situation.
import Cbuttons from './../utils/CustomButtons'
class MainScreen extends Component {
_onBtnClick = event => {
console.log("Click on Button");
}
render() {
return (
<View style={customStyles.mainContainer}>
<Cbuttons btnName="MainScreen" onPress={this._onBtnClick}/>
<Cbuttons btnName="ScreenTwo" onPress={this._onBtnClick}/>
<Cbuttons btnName="ScreenThree" onPress=
{this._onBtnClick}/>
</View>
);
}
}
export default MainScreen;
while inCustom Buttons clsss
class MyButtons extends Component {
constructor(props){
super(props);
this.state={btnName:this.props.btnName};
}
render(){
return(
<TouchableOpacity onPress={this.props.onPress} >
<Text style={yourStyles.buttonText}> {this.props.btnName}</Text>
</TouchableOpacity>
);
}
}
export default MyButtons;
I want to return btnName back via this.props.onPress

<Cbuttons btnName="MainScreen" onPress={ () => { this._onBtnClick(this.props.btnName)}/>
Turn that field into a function which calls the _onBtnClick function normally with a parameter.
Then you would reflect that in the _onBtnClick() method:
_onBtnClick = buttonName => {
console.log(`Click on Button ${buttonName}`);
}

This solved my problem, Thanks #mcpolo
class MyButtons extends Component {
render(){
return(
<TouchableOpacity onPress={()=>{this.props.onPress(this.props.btnName)}} >
<Text style={yourStyles.buttonText}> {this.props.btnName}</Text>
</TouchableOpacity>
);
}
}

Related

How can I pass a selected object from an array (firestore) to another class in react native?

I have a question about passing specific Objects from an array to another class in react native. If I press the button, all objects go to another class instead of the one I need, but I want the one which I pressed. Do I have to create a function for the selected object/ key or is it enough if I change something in the onPress={} method?
I need to change something here -> TouchableOpacity onPress={()=>this.props.navigation.navigate('detail', item,{})}> Item must be the document (firestore) with all the information I have, but how can I pass the object from the array only?
Here are also some pictures for a better understanding, thank you in advance
export default class foods extends Component {
constructor(props) {
super(props);
this.state = {
posts:[],
}
}
componentDidMount() {
StatusBar.setHidden(true)
this.subscriber = database.collection('users').onSnapshot(docs => {
let posts = []
docs.forEach(document => {
posts.push({
id: document.id,
...document.data(),
})
})
this.setState({posts})
console.log(posts)
})
}
render() {
return (
<ScrollView>
<View style={styles.container}>
{
this.state.posts.map((item) => {
return (
<View >
{
Object.keys(item.post).map((key) => {
return (
<View style={styles.card}>
<TouchableOpacity onPress={() => this.props.navigation.navigate('detail', item, {})}>
<Text>{item.firstName} {item.lastName}</Text>
<Image style={styles.cardImage} source={{ uri: item.post[key].image }} />
<Text>{item.post[key].essenname}</Text>
</TouchableOpacity>
</View>
)
})
}
</View>
)
})
}
</View>
</ScrollView>
);
}
}
export default class detail extends Component {
constructor(props) {
super(props);
this.state = {
post: [this.props.route.params]
}
};
componentDidMount() {
StatusBar.setHidden(true)
console.log('Array : ', this.state.post)
}
render() {
return (
<View style={styles.container}>
<ScrollView>
{this.state.post.map((item) => {
return (
Object.keys(item.post).map((key) => {
return (
<View style={styles.card}>
<Image style={styles.cardImage} source={{ uri: item.post[key].image }} />
<Text>{item.post[key].essenname}</Text>
</View>
)
})
)
})}
</ScrollView>
</View>
);
}
}
I want to pass either Post[0] or Post[1] but not both:
![](https://i.stack.imgur.com/3recX.png)
This is my output, which is the same output after navigating the item to the detail screen:
![](https://i.stack.imgur.com/WMqrd.png)
Detail screen on the right:
![](https://i.stack.imgur.com/gIX0V.png)
The document with the array 'post':
![](https://i.stack.imgur.com/dO1uQ.png)
There is no need to use Object.keys to loop trought your posts, just use item.post.
In your navigation params, just use a spred operator for the root key and pass the post selected: this.props.navigation.navigate('detail', {posts: {...this.state.posts, post: [p]}}).
In your detail component state your are missing to access the params, it should be:
this.state={
post:[this.props.route.params.posts]
}
and replace Object.keys with item.post

How to call function from different component bound to flatlist in React Native

I am creating a chat application in React Native that receives different "message types" as a response. One of them contains an array of buttons that I am currently rendering in a Flatlist in Component "ChatQuickReply" that looks like this:
import React from "react";
import {
StyleSheet,
FlatList,
View,
TouchableOpacity,
Text
} from "react-native";
class ChatQuickReply extends React.Component {
constructor(props) {
super(props);
}
renderItem({ item }) {
return (
<TouchableOpacity onPress={this._onPressQuickReply}>
<View style={styles.quickButton}>
<Text style={styles.quickButtonText}>{item.title}</Text>
</View>
</TouchableOpacity>
);
}
_onPressQuickReply = () => {
alert(Hello);
};
render() {
return (
<View>
<FlatList
data={this.props.buttons}
keyExtractor={(item, index) => "key" + index}
renderItem={this.renderItem}
/>
</View>
);
}
}
I am rendering this component in a different component also in a Flatlist which works fine.
The problem is, that I am not able to call the function that I am assigning to my TouchableOpacity. How can I call this function from a different component?
I think, what you can try to trigger onPress event for your TouchableOpacity component.
You need ref for this.
ref={touchableOpacity => this._touchableOpacity = touchableOpacity}
then when you want to launch onPress without clicking it just call
this._touchableOpacity.touchableHandlePress();
Depending on the relationship between both components, if the ChatQuickReply reply is a parent component, you can pass the function in the child as props and call it.
import React from "react";
class ChatQuickReply extends React.Component {
renderItem({ item }) {
return (
<TouchableOpacity onPress={this._onPressQuickReply}>
<View style={styles.quickButton}>
<Text style={styles.quickButtonText}>{item.title}</Text>
</View>
</TouchableOpacity>
);
}
_onPressQuickReply = () => {
alert(Hello);
};
render() {
return (
<View>
<FlatList
data={this.props.buttons}
keyExtractor={(item, index) => "key" + index}
renderItem={this.renderItem}
/>
**<ChildComponent clickParentFunction={this._onPressQuickReply} />**
</View>
);
}
}
class ChildComponent extends React.Component {
onClick = () => {
const {clickParentFunction} = this.props
clickParentFunction() // We can call it here
}
// We create a trigger to the onclick
}
or you can take the _onPressQuicklyReply function to the component that renders both components and pass it in to make it more generic
import OtherComponent from './Othercomponent';
class ParentComponent {
_onPressQuickReply = () => {
alert(Hello);
}
return (
<View>
<ChatQuicklyReply onParentFunction={this._onPressQuickly}>
<OtherComponent onParentFunctionCall={this._onPressQuickly} />
</View>
)
}

Can we use this.props.map as well as this.props.navigation in single class to navigate to another screen

I have used this.props.maps as well as this.props.navigation which is showing an error:
this.props.navigation.navigate is undefined object
Trying to navigate to another page by rendering the firebase database but getting error but the same code i tried by simple creating a view and navigating to another page then it is working
export default class ItemComponent extends Component {
constructor(props) {
super(props);
// need to bind `this` to access props in handler
this._onEditLibrary = this._onEditLibrary.bind(this);
}
static propTypes = {
items: PropTypes.array.isRequired
};
_onEditLibrary=()=> {
this.props.navigation.navigate('EditLibrary');
};
render() {
return (
<View style={styles.itemsList}>
<TouchableOpacity onPress={this._onEditLibrary}>
{this.props.items.map((item, index) => {
return (
<View key={index}>
<ImageBackground source={item.Image} style={ { height:150, width:150}}>
<Text style={styles.itemtext}>{item.Name}</Text>
</ImageBackground>
</View>
)
})
}
</TouchableOpacity>
</View>
);
}
}
Need to navigate to another page
Try this out
export default class ItemComponent extends Component {
constructor(props) {
super(props);
// need to bind `this` to access props in handler
this._onEditLibrary = this._onEditLibrary.bind(this);
}
static propTypes = {
items: PropTypes.array.isRequired
};
_onEditLibrary=()=> {
this.props.navigation.navigate('EditLibrary');
};
render() {
return (
<View style={styles.itemsList}>
{this.props.items.map((item, index) => {
return (
<TouchableOpacity key={index} onPress={this._onEditLibrary}>
<ImageBackground source={item.Image} style={ { height:150, width:150}}>
<Text style={styles.itemtext}>{item.Name}</Text>
</ImageBackground>
</TouchableOpacity>
)
})
}
</View>
);
}
}

How to re-render parent component React Native after update/edit in Child Component?

I get a problem to get new data in parent component (Profile) after update data in child component (ProfileEdit), here I create a simple script in order easy to understand, default component is Profile, why cannot show alert in Profile after back from ProfileEdit, please give advices or correct my script how to show alert after back from ProfileEdit.
Profile.js
export default class Profile extends Component {
componentDidMount() {
alert('Success');
}
toProfileEdit() {
this.props.navigation.navigate('ProfileEdit');
}
render() {
return (
<View>
<Button
onPress={() => this.toProfileEdit()}
title="Learn More" />
</View>
)
}
}
ProfileEdit.js
export default class ProfileEdit extends Component {
backTo() {
this.props.navigation.navigate('Profile');
}
render() {
return (
<View>
<Button
onPress={() => this.backTo()}
title="Learn More" />
</View>
)
}
}
Please anyone help me to solve this problem.
Thanks.
Profile already mount then componentWillMount will not call again on the back action. You can pass the function with prop action.
export default class ProfileEdit extends Component {
backTo() {
this.props.navigation.navigate('Profile');
}
render() {
return (
<View>
<Button
onPress={() => { this.props.something(); this.backTo()}}
title="Learn More" />
</View>
)
}
}
Pass function which name is something, call it after you can go back.

React-native passing component to another

I would like to pass one React component to my CustomTab component.
So i have something like this :
const FirstRoute = () => <View style={[ styles.container, { backgroundColor: '#ff4081' } ]} />;
const SecondRoute = () => <View style={[ styles.container, { backgroundColor: '#673ab7' } ]} />;
export default class Profile extends Component {
_renderScene = SceneMap({
first: FirstRoute,
second: SecondRoute,
});
render() {
return (
<CustomTab scenes={this._renderScene}/>
);
}
In my CustomTab i have :
export default class CustomTab extends React.Component {
_renderScene = this.props.scenes;
render() {
return (
<TabViewAnimated
style={styles.container}
navigationState={this.state}
renderScene={this._renderScene}
but this is not working, looks like passed parameter is wrong .It is possible to achieve that ?
Thx for any help.
You should set _renderScene property in constructor or other react component life cycle methods like.
constructor(props) {
super(props);
this._renderScene = this.props.scenes;
}
Your syntax is wrong, you need to assign _renderScene variable in render or constructor however there is not need for you to assign this.props.scenes to another class variable you could just directly use it
export default class CustomTab extends React.Component {
render() {
return (
<TabViewAnimated
style={styles.container}
navigationState={this.state}
renderScene={this.props. scenes}

Categories

Resources