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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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 codesandbox.io/s/…. Is there any way to fix it?
I've posted another SO question about this stackoverflow.com/questions/58774130/…
Thanks, @Erik R. IMHO, the docs could be enriched with this example
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 <PickOptions /> understands it as changed value and thus changeB(undefined) is executed and the initial value is deleted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.