Reza Reza - 8 months ago 86
React JSX Question

Show a dataset inside a picker

I am new in react native. I need to read some data from a file.js and shows them inside the Picker. I need just the "Title" inside the picker.
Here is my file.js:

export const mydata = [
{
"id": 1,
"Title": "Shiraz"
"prop": [
{
"id": 1,
"Title": "Test1",
}
]
},
];


My picker code is as below:

import {mydata} from "./myfile.js";

<Picker
style={{flex:1}}
data={mydata}
mode="dropdown"
selectedValue={this.state.PickerValueHolder}
onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >
{
data.map((item, index) => {
return (<Item label={item} value={index} key={index}/>)
}
)
}
</Picker>


In the above code the data is not defined and I don't know how to manage it in such a way, that it shows the file content correctly.
Can you help me how can I show my "Title" data inside the picker?

Answer Source

You have to change your function depending on the data you want to display. e.g. your data looks like that

export const mydata = [
   {
   "id": 1, // will be shown as value
   "Title": "Shiraz" // will be shown as your label 
   "prop": [
              {
                "id": 1,
                "Title": "Test1",
              }
           ]
   },
   "id": 2, // will be shown as value
   "Title": "Shiraz2" // will be shown as your label 
   "prop": [
              {
                "id": 1,
                "Title": "Test1",
              }
           ]
   },
   ];

Then you need to change your component to:

    <Picker
    >
       {this.renderPickerItems(mydata)}
   </Picker>

and i would recommend to create a new function to render items:

renderPickerItems(data) {
    const elements = data.map((val, index) => {
        return <Picker.Item key={index} label={val.Title} value={val.id} /> 
    });
    return elements; 
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download