Home > Net >  unable to loop the data using map
unable to loop the data using map

Time:06-28

I'm trying to display the array of data in select box using map in react material ui, and getting TypeError: Cannot read properties of undefined (reading 'map') for the below code, Any help on what wrong is in my code. below is the array i am trying to display:

"secondClassCalmPrices":[["Kan ej ombokas","431","SEK","Företagspris"],["Kan ombokas","525","SEK","Företagspris"],["Kan återbetalas","724","SEK","Företagspris"]]

material ui select code:

<Select
    labelId="demo-simple-select-standard-label"
    id="demo-simple-select-standard"
    value={props.legs.secondClassCalmPrices}
    label="ticket type"
    variant="standard"
    className="calm-class-select"
>
    {props.legs.secondClassCalmPrices.map((info) => {
      return <MenuItem>{info}</MenuItem>;
    })}
</Select>

CodePudding user response:

The most common error in these situations is that component has been rendered and some milliseconds later the props are loaded. So the very first time the component tries to render the Select component, but props are not initialized yet and you see this error.

In such cases, where there is this delay of props being filled, you should use sth like this

{props.legs && props.legs.secondClassCalmPrices ?
<Select
                        labelId="demo-simple-select-standard-label"
                        id="demo-simple-select-standard"
                        value={props.legs.secondClassCalmPrices}
                        label="ticket type"
                        variant="standard"
                        className="calm-class-select"
                      >
                        {props.legs.secondClassCalmPrices.map((info) => {
                          return <MenuItem>{info}</MenuItem>;
                        })}
                      </Select>
: null}

CodePudding user response:

You can use optional chaining to counter this

<Select
                    labelId="demo-simple-select-standard-label"
                    id="demo-simple-select-standard"
                    value={props.legs.secondClassCalmPrices}
                    label="ticket type"
                    variant="standard"
                    className="calm-class-select"
                  >
                    {props?.legs?.secondClassCalmPrices?.map((info) => {
                      return <MenuItem>{info}</MenuItem>; //needs to be modified
                    })}
                  </Select>

Plus you cannot render an array inside JSX element. you may need to use map function twice to render JSX using "secondClassCalmPrices".

  • Related