0
<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.

3 Answers 3

0

you can do a simple Array.map() onto the options property as it will return a new mapped array.

<MultiSelect
  id="MultiSelect-1"
  label="Label"
  onChange={function noRefCheck(){}}
  options={paymentTypes.map(paymentType => ({
    label: `${intl.formatMessage({
      id: `fld.value.receivablesreport.payment.types.${paymentType.toLowerCase()}`,
    })}`,
    name: `${paymentType}`,
    value: `${paymentType}`,
    checked: checkedPaymentTypes
  }))}
/>

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.

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

Comments

0

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.

<MultiSelect
  id="MultiSelect-1"
  label="Label"
  onChange={function noRefCheck(){}}
  options={paymentTypes.map((type) => ({
    label: intl.formatMessage({
      id: `fld.value.receivablesreport.payment.types.${type.toLowerCase()}`,
    }),
    name: type,
    value: type,
    checked: checkedPaymentTypes,
  }))}
/>

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.

options={paymentTypes.map((type) => {
  const { id } = type;
  const label = intl.formatMessage({ id: `fld.value.receivablesreport.payment.types.${id.toLowerCase()}` });
  return { label, name: id, value: id, checked: checkedPaymentTypes };
})}

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.

const mapPaymentTypesToOptions = (paymentTypes, checkedPaymentTypes, intl) => {
  return paymentTypes.map((type) => {
    return {
      label: intl.formatMessage({
        id: `fld.value.receivablesreport.payment.types.${type.toLowerCase()}`,
      }),
      name: type,
      value: type,
      checked: checkedPaymentTypes,
    };
  });
};


<MultiSelect
  id="MultiSelect-1"
  label="Label"
  onChange={function noRefCheck(){}}
  options={mapPaymentTypesToOptions(paymentTypes, checkedPaymentTypes, intl)}
/>

3 Comments

That works great thank you very much! I am trying out the checked part but cant seem to get it to work. i set this const [checkedPayments, setCheckedPayments] = useState(Array(2).fill(true)); and then i do this in the handle change function. const handleChange = () => { const updatedCheckedState = checkedPayments.map((item, index) => setCheckedPayments[index] === item ? !item : item ); setCheckedPayments(updatedCheckedState); }; But all of this doesnt update the state. I am not sure what i am doing wrong here.
To better understand your problem and provide accurate assistance, could you please share the complete code related to the issue? Having access to the full code will help me analyse the context and identify any potential errors. You can either include the code directly in your comment or share it via a code-sharing platform like GitHub or Pastebin.
pastebin.com/dQxmsehA Here i listed the full code for the multiselector.
0

Here is a suggestion since it seems you are confused about how to approach your problem and I have no clue how you are structuring your data.

I used the MultiSelect component from primereact. I am not sure about yours thought.

For the Data Structure, in your HashMaps, you don't need to use the checked property. You can keep the label property since it stores the translated value and the value property.

import React, { useState } from "react";
import { MultiSelect } from "primereact/multiselect";

const payments = [
  { label: "card", value: "card" },
  { label: "cash", value: "cash" },
  { label: "paypal", value: "paypal" }
];

const defaultCheckedPayments = ["card", "paypal"];

export default function BasicDemo() {
  const [checkedPayments, setCheckedPayments] = useState(
    defaultCheckedPayments
  );

  return (
    <div className="card flex justify-content-center flex-column align-items-center gap-2">
      <MultiSelect
        value={checkedPayments}
        onChange={(e) => setCheckedPayments(e.value)}
        options={payments}
        optionLabel="label"
        placeholder="Select Payments"
        className="w-full md:w-20rem"
      />
      {checkedPayments && (
        <>
          <ul>
            {checkedPayments.map((payment) => (
              <li key={`payment-${payment}`}>{payment}</li>
            ))}
          </ul>
        </>
      )}
    </div>
  );
}

Access full code here

Comments

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.