Reputation: 53
I have created a custom ListComponent and use in a DashboardComponent. I have import the ListComponent and passed the data in it and list will render in the DashboardComponent. I have create function to get the id of specific object. so, whenever I click on any list, got the id in ListComponent. But, I want to pass this id on DashboardComponet which I unable to do it.
ListComponet Code:
import React, { Component } from "react";
import {Text,View} from "react-native";
import { List,ListItem} from "native-base";
export default class ListComponent extends Component {
constructor(props) {
super(props);
this.state = {
opID: "",
};
}
getUserId = (id) => {
console.log("id",id);
this.setState({opID:id})
};
render() {
return (
<View style={optionUI.container}>
<List>
{this.props.data.map((Opt, i) => (
<ListItem
key={Opt.id}
opID = {this.props.opID}
noBorder
onPress={() =>
this.getUserId(Opt.id)
}
>
<Text>{Opt.title}</Text>
</ListItem>
))}
</List>
</View>
);
}
}
DashboardComponent:
import React, { StrictMode, Component } from "react";
import { View} from "react-native";
import ListComponent from "../components/Option";
export default class DashboardComponent extends Component {
constructor(props) {
super(props);
this.state = {
userList: [...data...],
};
}
componentDidMount() {
}
render() {
const {userList} = this.state;
console.log("users",this.props);
return (
<StrictMode>
<View style={dashboardUI.optionSection}>
<ListComponent data={userList.options} />
</View>
</StrictMode>
);
}
}
data:
userList={
"options": [
{
"id": 1,
"optId":1,
"title": "Reliance Industries Limited",
"subtitle": "Multinational conglomerate company"
},
{
"id": 2,
"optId":2,
"title": "Aditya Birla Group",
"subtitle": "Corporate group company"
},
{
"id": 3,
"optId":3,
"title": "Adani Group",
"subtitle": "Multinational conglomerate company"
},
{
"id": 4,
"optId":4,
"title": "Piramal Group",
"subtitle": "Conglomerate company"
},
{
"id": 5,
"optId":5,
"title": "Hindustan Zinc",
"subtitle": "Mining company"
}
]
}
Upvotes: 0
Views: 832
Reputation: 505
Use props In DashboardComponent pass function
<ListComponent data={userList.options} onClick = {this.onClickItem.bind(this)} />
and get with function
onClickItem = (id) => {
console.log("id...",id);
}
In ListComponent class call the function onPress
getUserId = (id) => {
this.props.onClick(id) //Call the function
this.setState({opID:id})
};
Upvotes: 1