Francisco Maria Calisto Francisco Maria Calisto - 2 months ago 6
React JSX Question

Selection of Linked Selections

I am using the React + Redux + Router stack and by this time I have got a simple React component where I am trying to develop a selection of linked selection with this behavior example.

In fact my component can easily consume this variable:

var VAR_OPTIONS_OLD = [
{value: 1, name: '1'},
{value: 2, name: '2'},
{value: 3, name: '3'},
{value: 4, name: '4'},
{value: 5, name: '5'},
]


Where the component is this one:

<Field
type={Select}
options={VAR_OPTIONS_OLD}
optionValue="value"
id="someID"
class="col-12"
i18n={i18n.someID}
/>


Now I want my both selects consume this variable:

var VAR_OPTIONS_NEW = {
optionA: {
name: 'Option A',
suboptionA: ['Suboption A1', 'Suboption A2', 'Suboption A3']
},
optionB: {
name: 'Option B',
suboptionB: ['Suboption B1', 'Suboption B2', 'Suboption B3']
},
optionC: {
name: 'Option C',
suboptionC: ['Suboption C1', 'Suboption C2', 'Suboption C3']
}
}


So that I can take advantage of having 2 linked selects depending each other.

Answer

In your view component code:

At top:

const _ = require('lodash');
const VAR_OPTIONS_NEW = ... // The one you provided.

in render():

const firstValue = ... // this should come from your Store (e.g. this.props.firstValue).
const secondValue = ... // this should come from a Store

const firstOptions = _.map(VAR_OPTIONS_NEW, (v, k) => ({ value: k, name: v.name });

let secondOptions = [];
if (VAR_OPTIONS_NEW[firstValue]) {
    secondOptions = VAR_OPTIONS_NEW[firstValue].suboptions.map(
        (name, index) => ({ value: index, name: name })
    );
}
...
<Field
    options={ firstOptions }
    optionsValue={ firstValue }
    onChange={/* is your onChange event connected to Store? */}
    ...
/>
<Field
    options={ secondOptions }
    optionsValue={ secondValue }
    onChange={/* is your onChange event connected to Store? */}
    ...
/>