How to change dropdown options based on value selected previously?

626 Views Asked by At

I am using tcomb package for forms https://github.com/gcanti/tcomb-form-native I have 2 dropdowns i.e I have created 2 enums. Now 1st dropdown i.e enum has 3 options A, B, C in dropdown list. Now if user selects option A from 1st enum then in 2nd enum it should display P, Q, R as these 3 dropdown options for 2nd enum if and only if option A is selected from dropdown. Now if option B is selected 2nd enum should options X, Y, Z similarly if option C is selected from dropdown list from 1st enum then L, M, N options should be shown.

So how can I dynamically change enum fields based on option selected previously ?

1

There are 1 best solutions below

0
OWS On

Maybe it helps others as well. One way to achieve this is using the tcomb variables from state, like

this.state = {
  field1: t.enums({'A':'AA', 'B':'BB', 'C':'CC'},'field1'),
  field2: t.enums({},'field2')
}

let MyForm = t.struct({
  field1: this.state.field1,
  field2: this.state.field2
)}

and in your onChange function you change the dropdown of field2 based on the value of field1, as follows:

onChange(value) {
 if (value.field1 == 'A')
  this.setState(field2: t.enums({'P':'PP','Q':'QQ','R':'RR'}, 'field2')
 else if (value.field1 == 'B')
 ...
}

finally, in your render function you write:

<Form type={MyForm} onChange={this.onChange} />