3

How to populate options in react-select using the below JSON data which doesn't have value and label properties?

[       
    {
        "sortCode": "55-77-42",
        "accountNumber": "08488234",
        "accountType": "Savings Account",
        "accountName": "Mannuel Sam"
    },
    {
        "sortCode": "12-43-98",
        "accountNumber": "12365432",
        "accountType": "Savings Account",
        "accountName": "John Cena"
    },
    {
        "sortCode": "87-20-51",
        "accountNumber": "76491234",
        "accountType": "Savings Account",
        "accountName": "Shweta Pandey"
    },
    {
        "sortCode": "56-73-39",
        "accountNumber": "09865479",
        "accountType": "Savings Account",
        "accountName": "Prerna Singh"
    }
]
3
  • What specific part do you need help with? Is it the functional component part or populating data? Please post what you've tried already. Commented Mar 4, 2021 at 6:00
  • What do you want that react select to look like? What should be the dropdown labels and values? You have 4 values in each element, a dropdown like react select only takes 2. Commented Mar 4, 2021 at 6:10
  • 1
    Yes it does,thank you Commented Mar 19, 2021 at 8:46

1 Answer 1

7

You can provide getOptionLabel and getOptionValue props to react-select:

import React from "react";
import Select from "react-select";

const options = [
  {
    sortCode: "55-77-42-56",
    accountNumber: "0848890234",
    accountType: "Savings Account",
    accountName: "XYZ Sam"
  }
  // ...
];

export default () => {
  const [value, setValue] = React.useState({});

  return (
      <Select
        name="accounts"
        options={options}
        value={value}
        onChange={setValue}
        getOptionLabel={(option) => option.accountName}
        getOptionValue={(option) => option.accountNumber} // It should be unique value in the options. E.g. ID
      />
  );
};

Demo

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

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.