I am using react for a school project. The dynamic data does not binds to Options from Ant Design, react js. The result is an empty option list. In actual the data comes from an external API. For testing purpose I assigned the data the state variable. The data comes in 2D array, so I am mapping through the data twice.
import { useEffect, useState } from "react";
import { Select } from "antd";
const { Option } = Select;
const Complete = () => {
const [list, setPersons] = useState([
[
{
id: 1,
personName: "Owan",
},
{
id: 2,
personName: "More",
},
{
id: 3,
personName: "Jaila",
},
{
id: 4,
personName: "Eerov",
},
],
[
{
id: 5,
personName: "Rell",
},
{
id: 6,
personName: "Juko",
}
]
]);
useEffect(() => {
console.log(list);
}, []);
return (
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{list.map((l) => {
l.map((person) => {
console.log(person);
<Option value={person.id}>
{person.personName}
</Option>;
});
})}
</Select>
);
};
export default Complete;
>Solution :
Try with the following code:
import { useEffect, useState } from "react";
import { Select } from "antd";
const { Option } = Select;
const Complete = () => {
const [list, setPersons] = useState([
[
{
id: 1,
personName: "Owan"
},
{
id: 2,
personName: "More"
},
{
id: 3,
personName: "Jaila"
},
{
id: 4,
personName: "Eerov"
}
],
[
{
id: 5,
personName: "Rell"
},
{
id: 6,
personName: "Juko"
}
]
]);
useEffect(() => {
console.log(list);
}, [list]);
return (
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a person"
optionFilterProp="children"
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{list.map((l) => (
<>
{l.map((person) => (
<Option value={person.id}>{person.personName}</Option>
))}
</>
))}
</Select>
);
};
export default Complete;
