0

I am trying to populate a React Native picker with an array of strings I have stored in my state:

  constructor(props) {
    super(props);
    this.state = {
      designations: ["test", "test2"],
      ...
    }
    ...
  }

What I would like, is for my Picker element to populate the Picker.Items from the values inside this array in my state.

Here is my picker:

   <Picker
        selectedValue={this.state.designations[0]}
        onValueChange={(itemValue, itemIndex) => this.setState({ designation: itemValue })}
        
        {...Object.keys(this.state.designations).map((key) => {
                  return (<Picker.Item label={this.state.designations[key]} value={key} key={key}/>)
              })}
    />

I do not receive an error with this configuration, however the Picker has no items at all.

After reading This thread about doing exactly what I'm trying to do, I notice that they do not have a spread operator (...) infront of "Object" in theirs. However, when I try and do that in my code I recieve the following error:

'...' expected.

I have also tried the following (also from that thread):

         {...this.state.designations.map((item, index) => {
                 return (<Picker.Item label={item} value={index} key={index}/>) 
         })}

But unfortunately it is exactly the same as the above issue. I get an error if I do not use the spread operator, and when I do use the spread operator the picker list is not populated.

Any help or directions to look would be very welcome.

2
  • 1
    Look at the original thread. The Picker.Item elements are children of the Picker element, so they go in between the <Picker> and </Picker> opening and closing tags. Also, state.designations is an array so the second way of mapping you show is the correct one, without using Object.keys. Commented Jul 14, 2020 at 16:29
  • @BillDoughty you're correct! I feel really silly and I'm not sure how I missed that. I would mark your solution as the answer, but I am unable to since it's a comment. Cheers! Commented Jul 14, 2020 at 16:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.