Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to populate React Select dropdown from Json Object

I am facing an issue with populating react-select dropdown from JSON object, putting the code below for reference. Any help would be highly appreciated.

import React, { useState, useEffect } from 'react'
import Select from 'react-select';
function App() {

  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("/listEmployees")
      .then((response) => response.json())
      .then((data) => {
        // put the employees data in the state
        setData(JSON.parse(data.empPartition));
        console.log(JSON.parse(data.empPartition));
      });
  }, []);

  return (
    <div>
       <Select
        options={data}
       />
    </div>
  )
}

export default App;

The JSON Object on the console looks like this

{0: 'John', 1: 'Davis', 2: 'Sherry'}
0: "John"
1: "Davis"
2: "Sherry"

The dropdown shows up on page but doesn’t work with the following error
props.options.map is not a function
TypeError: props.options.map is not a function
at buildCategorizedOptions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

So, considering your data shape as;

{0: 'John', 1: 'Davis', 2: 'Sherry'}

And the value options that react-select accepts is

{ label: string, value: string }[]

You’d have to first transform your data to the options object that react-select understand;

const input = { 0: 'John', 1: 'Davis', 2: 'Sherry' };

const transformed = Object.entries(input).map(([key, value]) => ({
  label: value,
  value: value
}));

console.log(transformed);

Then you can set transformed value to your data state and pass it through option props to your Select component.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading