0

I am trying to display array values into select tag, but all the array values displayed as single value. Please see below logic I added. Data is dynamic, I am getting data from backend like this ["Sankranti", "Sankranti 1"].

const [eventNameList, setEventNameList] = useState([])

var eventList = eventNameList.length > 0 ? 
                eventNameList.map((item,i) => {
                    console.log('list: ', item)
                    return (
                        <option>{item}</option>
                        )
                    })
                    :
                    'No Events'
<select>
      {eventList}
</select>

please find below console screen shot

enter image description here

enter image description here

3
  • could you print eventNameList outside the loop and show be the result? Commented Jan 15, 2021 at 3:03
  • 1
    I think your result is nested array, that's why you are getting an array in a loop. Could you show us your result returned from api. Commented Jan 15, 2021 at 3:06
  • outside loop i added eventNameList. it displayed in console like this. eventNameList: [Array(2)] 0: (2) ["Sankranti", "Sankranti 1"] length: 1 proto: Array(0) Commented Jan 15, 2021 at 3:30

1 Answer 1

1

It looks that your list is nested inside another array so to fix this you could use flatMap instead of map

or you could just iterate throw the first element inside your nested array

const [eventNameList, setEventNameList] = useState([])

var eventList = eventNameList.length > 0 ? 
                eventNameList[0].map((item,i) => {
                    console.log('list: ', item)
                    return (
                        <option>{item}</option>
                        )
                    })
                    :
                    'No Events'
<select>
      {eventList}
</select>
Sign up to request clarification or add additional context in comments.

4 Comments

I got same results previous results.
try this one instead of flatMap try eventNameList[0].map
Thanks this logic eventNameList[0].map worked. could you please let me how this logic works.
you are welcome :), because it returns a subarray that includes [["Sankranti", "Sankranti 1"], "another data you do not need"] so as you mention you want the list in the first index only that contains your array so you can access it by its index in the outer array

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.