Flippy
Flippy

Reputation: 211

Selecting an Item of React Native Drop Down Picker in Class Component does not work

I am using a React Native Class Component and I want to integrate a Drop Down Picker, therefore I choosed the react-native-dropdown-picker. The Drop Down Picker is displayed properly, but choosing a value from the menu crashes my app.

import DropDownPicker from 'react-native-dropdown-picker';

class MyClass extends Component {
   constructor(props) {
      super(props);
      this.state = {
         open: false,
         value: ['val1', 'val2', 'val3'],
         items: [
            {label: 'Value1, value: 'val1'},
            {label: 'Value1_1, value: 'val1_1', parent: 'val1'},
            {label: 'Value1_2, value: 'val1_2', parent: 'val1'},
            {label: 'Valu21, value: 'val2'},
            {label: 'Value2_1, value: 'val2_1', parent: 'val2'},
            {label: 'Value2_2, value: 'val2_2', parent: 'val2'},
            {label: 'Value3, value: 'val3'},
            {label: 'Value3_1, value: 'val3_1', parent: 'val3'},
            {label: 'Value3_2, value: 'val3_2', parent: 'val3'}],
      }
      ...
      handleValueChanged = (newVal) => {
         setState((state => ({ value: newVal }));
      }
      render() {
         return(
            ...
            <DropDownPicker
            open={this.state.open}
            value={this.state.value}
            items={this.state.items}
            setOpen={(open) => this.setState({ open })}
            setValue={this.handleValueChanged}
            setItems={(items) => this.setState({ items})}
            mode="BADGE"
            />
            ...
         )
      }
   }
}

I receive a TypeError: Type error and when I want to print my new selected values to console using console.log(newVal) within my handleValueChanged function a whole function is printed (and therefore the type error of course, because I want to update an array).

function (state) {
   if (multiple) {
   ...
   }
}

Also the original documentation for Class Components does not seem to work. So the main question is: How do I manage to set my value using setValue properly?

Upvotes: 0

Views: 612

Answers (1)

Flippy
Flippy

Reputation: 211

I had to change this

handleValueChanged = (newVal) => {
   setState((state => ({ value: newVal }));
}

to

handleValueChanged = (newVal) => {
         setState((state => ({ value: newVal(state.value)}));
}

Upvotes: 0

Related Questions