I am a beginner in ReactJS and I have a problem with Selects. I have a Select
that renders some plants and bees with MenuItem
.
What I need is that Select already comes with some values marked in the list of bees
and plants
.
If the user clicks on New Property the selects are blank, but the user clicks on any property to edit, then the selects must be marked with checked.
I hope I managed to explain it correctly. Here’s my code I put into CodeSandBox
Here’s the simulation of my bee database:
{ "data": [ { "id": "1", "type": "bee-databases", "attributes": { "species-name": "Africanizada (Apis mellifera)" } }, { "id": "2", "type": "bee-databases", "attributes": { "species-name": "Abelha-cachorro, Arapuá, Irapuá (Trigona spinipes)" } }, { "id": "3", "type": "bee-databases", "attributes": { "species-name": "Andorinha, Benjoi (Scaptotrigona polysticta)" } } ] }
Here’s the simulation of my plant database:
{ "data": [ { "id": "1", "type": "plant-databases", "attributes": { "species-name": "Cana-de-açucar" } }, { "id": "2", "type": "plant-databases", "attributes": { "species-name": "Citros" } }, { "id": "3", "type": "plant-databases", "attributes": { "species-name": "Eucalipto" } } ] }
Here’s the simulation of my properties database:
{ "id": "45", "type": "properties", "attributes": { "farmer-name": "João Galli", "name": "Nova Propriedade", "address": "Rua teste", "total-planted-area": "100", "total-forest-area": "40", "apiaries-in-use": 20, "plants": [ [ { "id": 46, "kind": "Cana-de-açucar" } ] ], "accepted-bees": [ [ { "id": 46, "kind": "Africanizada (Apis mellifera)" } ] ] } }
Advertisement
Answer
If I understand correctly, the problem is that the select has [Object object]
instead of the actual label.
If so, the problem is that the dropdown expects to get an array of strings for the value
prop. Means that beeSelect
should be an array of string, but it’s actually an array of (array of) of bees
e.g.
"accepted-bees": [ [ { "id": 46, "kind": "Africanizada (Apis mellifera)" } ] ]
So, the .map
should looks a bit different
const _selectedBees = item.attributes["accepted-bees"].map((bee) => bee[0].kind);
(Same goes to the plants)
Notes:
- Why
accepted-bees
is an array of arrays if anyway it has only one item (the child array) - There is not point of doing
.map((bee) => bee)
. It returns the same value it gets.