Emil Mammadov
Emil Mammadov

Reputation: 468

React-Native Picker cannot initialize a default value

I have a Picker and I have to show my default value on initialization of Picker but selectedValue is not firing at first call.

That is my Picker:

<Picker
    selectedValue={this.props.expense.currency}
    onValueChange={(val) => {
        let expenses = [...this.props.expense];
        expenses[index].currency = val;
        this.props.setExpense(expenses);
    }}>

    <Picker.Item label='Select Money' value='default'/>
    {
        loginType.currency.map((i) => {
            return (<Picker.Item label={i.TYPE} value={i}/>)
        })
    }
</Picker>

this.props.expense.currency returns:

{
    CODE: '2',
    TYPE: 'EUR'
}

It has to come with 'EUR' as default. But it comes with 'Select Money'.

It is been a day and I couldn't find any solution. I researched for defaultValue but there is nothing like that on Github pages. Any solution or workaround?

Upvotes: 1

Views: 1579

Answers (1)

CampbellMG
CampbellMG

Reputation: 2220

You should use something that is comparable for the picker item value prop.

I am assuming what is happening here is that the object comparison between this.props.expense.currency and the value prop on each Picker.Item is failing so it is defaulting to the first. Try mapping the value to the code rather than the full object, like this:

<Picker
    selectedValue={this.props.expense.currency.CODE}
    onValueChange={(val) => {
        let expenses = [...this.props.expense];
        let newVal = loginType.currency.find(item => item.CODE === val)
        expenses[index].currency = newVal;
        this.props.setExpense(expenses);
    }}>

    <Picker.Item label='Select Money' value='default'/>
    {
        loginType.currency.map((i) => {
            return (<Picker.Item label={i.TYPE} value={i.CODE}/>)
        })
    }
</Picker>

Upvotes: 4

Related Questions