1

I'm using react-select with react-final-form and I need to have two selects, where the selected option in the first select dynamically sets the options for the second select. For example, when option One is selected in the first select, the second select gets options One A and One B.

These selects are used in an array. Here is my codesandbox with initial setup https://codesandbox.io/s/react-final-form-field-arrays-e4mm6?fontsize=14.

I've found two similar examples, but I don't know how to adapt them to my use case.

First, I've found this example for react-final-form which sets field's value using createDecorator, but it's used for the value of the field and not the options prop.

Second, I've found this example for react-select which sets options dynamically using state, but I don't know how I can adapt it to my case, considering field arrays.

I would appreciate any help.

jupiteror
  • 1,085
  • 3
  • 24
  • 50

1 Answers1

3

Interesting, problem. Here ya go. I created a <PickOptions/> component that watches the first field and provides the options to the second. It also clears the second field when the value of the first changes, which seemed like something you'd want. You could also set it to the first option in the array or something...

Edit  React Final Form - Field Arrays SO

Erik R.
  • 7,152
  • 1
  • 29
  • 39
  • Hi Erik, I have one more question regarding your answer with PickOptions. Unfortunately, it doesn't work, if I want to initialize the values from the state. If I delete `changeB`, the values are initialized, but then the selected option in the second select is not updated based on the value of the first select. (I also have the first option in each array set as the default value.) Here is the link to the example https://codesandbox.io/s/react-final-form-field-arrays-so-9ihm0?fontsize=14. Is there any way to fix it? – jupiteror Nov 08 '19 at 14:07
  • I've posted another SO question about this https://stackoverflow.com/questions/58774130/conditional-dropdowns-with-react-select-in-react-final-form-initialized-from-the – jupiteror Nov 08 '19 at 21:44
  • Thanks, @Erik R. IMHO, the docs could be enriched with this example – Hola Jul 19 '21 at 16:46
  • Hi Erik, what would be the approach to extend your example to except initialValues? I am struggling to figure it out. When initialValues are provided, the useEffect within understands it as changed value and thus changeB(undefined) is executed and the initial value is deleted – Hola Jul 29 '21 at 18:49