<MultiSelect
id="MultiSelect-1"
label="Label"
onChange={function noRefCheck(){}}
options={[
{
label: 'Checkbox 1',
name: 'accounts',
value: 'Checkbox 1'
},
{
label: 'Checkbox 2',
name: 'accounts',
value: 'Checkbox 2'
},
]}
/>
I have this multi selector and i have an array passed down from another component to this one. i need to basically map that data into options listen above so that name is taken from the mapping function rather than using index of array.
This is what i have done so far. Its manual work but i want to know whether i can do this via the map method.
<MultiSelect
id="MultiSelect-1"
label="Label"
onChange={function noRefCheck(){}}
options={[
{
label: `${intl.formatMessage({
id: `fld.value.receivablesreport.payment.types.${paymentTypes[0].toLowerCase()}`,
})}`,
name: `${paymentTypes[0]}`,
value: `${paymentTypes[0]}`,
checked: checkedPaymentTypes,
},
{
label: `${intl.formatMessage({
id: `fld.value.receivablesreport.payment.types.${paymentTypes[1].toLowerCase()}`,
})}`,
name: `${paymentTypes[1]}`,
value: `${paymentTypes[1]}`,
checked: checkedPaymentTypes,
},
]}
/>
I tried doing mapping inside the options but it always fails. It will render the checkboxes but it wont render the value or the labels. Any help is appreciated I am a junior developer so still learning and havent faced this issue before.
2
Answers
you can do a simple Array.map() onto the
options
property as it will return a new mapped array.Anyway, you can separate the options mapping to another function, then invoke it inside the
options
property so the JSX would be more cleaner and shorter.Hope it helps.
This is how you can dynamically generate the options based on the data in the
paymentTypes
array, avoiding the need for manual entry and reducing code duplication.To improve the code further, you can consider destructure the properties instead of accessing the properties through dot notation incase
paymentTypes
is a list of hashMaps.You can also consider separating the mapping logic into a separate function: If the mapping logic becomes more complex or reusable. This improves readability and maintainability of your code.