mrbranden
mrbranden

Reputation: 1050

React Native Picker component with React hook: cannot pass value of Picker to parent

I'm using the Picker component of React Native to make a selection. Unfortunately, it is not working; I cannot get the value of onValueChange to pass upwards to handleChangeCharacter. Here is what I have so far:

  const [characterIndex, selectCharacter] = useState('0')

  const handleChangeCharacter = ({ e }) => {
    console.log('e', e)
    selectCharacter(e)
  }

  const cStyle = "Style: " + characters[characterIndex].cStyle
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Picker selectedValue={characterIndex} onValueChange={handleChangeCharacter}>
          {
            characters.map((character, index) => {
              return (
                <Picker.Item label={character.name} value={index} key={index} />
              )
            })
          }
        </Picker>
...
...
...

I'm using the React Hook to set the value of "characterIndex". Unfortunately, 'e' is always 'undefined.'

Any help is appreciated.

Upvotes: 0

Views: 649

Answers (1)

Junius L
Junius L

Reputation: 16132

The problem is in your handleChangeCharacter, you are destructuring but the onValueChange doesn't pass object with property e. docs

onValueChange - Callback for when an item is selected. This is called with the following parameters:

itemValue: the value prop of the item that was selected

itemPosition: the index of the selected item in this picker

// remove destructuring
const handleChangeCharacter = (value, index) => {
  console.log('value', value, index) // equals to index which is set here value={index}
  selectCharacter(value)
}

Upvotes: 1

Related Questions