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
2
Answers
So, considering your
data
shape as;And the value
options
that react-select accepts isYou’d have to first transform your
data
to theoptions
object that react-select understand;Then you can set
transformed
value to yourdata
state and pass it throughoption
props to your Select component.You need to sent an array of object with the required structure like
So your code would be