React Native Picker moves back to first item

Viewed 3965

This works as expected, where the picker stays on the selected item...

<Picker
    selectedValue={this.state.person}
    onValueChange={(itemValue) => this.setState({person: itemValue})}
    style={styles.picker}>
    {Object.keys(coWorkers)
        .map((result, index) =>
            <Picker.Item
                label={`${coWorkers[result].name}(${coWorkers[result].likes})`}
                value={coWorkers[result].name}
                key={index}
            />
        )
    }
</Picker>

I want to get multiple key/values from the coWorkers object in this.setState, so I am trying this...

<Picker
    selectedValue={this.state.person}
    onValueChange={(itemValue) => this.setState({person: itemValue.name, likes: itemValue.likes})}
    style={styles.picker}>
    {Object.keys(coWorkers)
        .map((result, index) =>
            <Picker.Item
                label={`${coWorkers[result].name} (${coWorkers[result].likes})`}
                value={coWorkers[result]}
                key={index}
            />
        )
    }
</Picker>

However, now the picker jumps back to the top (this.state is being correctly updated though).

3 Answers

If someone else has this problem and the solutions above are not working, it might be because you don't have the selectedValue flag set to something:

// You can replace the null with an actual value in your array(check to see it's exact)
const [toLanguage, setToLanguage] = useState(null); 


selectedValue={toLanguage}

Your itemValue.name is not matching your coWorkers[result]

Related