Lalani Gunathilaka
Lalani Gunathilaka

Reputation: 87

React-select with formik: changing options passed to select

I have two selects in my form one of them is for the origin and the other is for destination. I have two arrays one for origin with all origins and other for destinations which is an array inside array matching the relevant destinations for a given origin. I pass these arrays to options field in react select. When my origin change I need to change the options in Select for destination to the relevant array inside destination. And when the origin change again I need the select for destination to be empty. However If already has a destination selected when I change the origin the destination array inside react select options change but the text shown in the react-select does not change. Any help is appreciated. Thank you

CodeSandbox Link: https://codesandbox.io/s/hopeful-tdd-8huwo?file=/src/App.js

<Select
    options={origins}
    placeholder="Origin"
    value={origins ? origins.find((option) => option.value === props.values.origin) : ''}
    onChange={(option) => {
        props.setFieldValue('origin', option.value);
        props.setFieldValue('destination', '');
    }}
/>
<Select
    options={
        props.values.origin == ''
            ? []
            : destinations[origins.findIndex((entry) => props.values.origin == entry.value)]
    }
    options={destinations}
    placeholder="To"
    value={
        destinations
            ? destinations.find((option) => option.value === props.values.destination) && null
            : ''
    }
    onChange={(option) => props.setFieldValue('destination', option.value)}
/>
                        

Upvotes: 1

Views: 2428

Answers (2)

shiponcs
shiponcs

Reputation: 1677

Because you're not updating the value of destination field by checking if props.values.destination is "" or not. Here is the change you can make to make it work:

value={
          destinations && props.values.destination
            ? destinations.find(
                (option) => option.value === props.values.destination
              ) && null
            : ""
        }

Edited sandbox Link

Upvotes: 1

mehowthe
mehowthe

Reputation: 841

Some notes:

  • second field has two options props
  • use === for comparing values (also second select)

It would be helpful to provide a Codesandbox for this issue, but from your description seems that you would like to move items from one list to another, for this there are some nice components in different libraries called Transfer/Transfer List:

If you would like to do this from the scratch - there's an example on the Formic docs, how to manage dependency between field

Upvotes: 0

Related Questions