Home > Net >  TypeError: (...).map is not a function
TypeError: (...).map is not a function

Time:10-15

I'm new to both javascript and react so there may be many things wrong here.

I have an interface LiquidityPosition that I'm trying to display as components through my LiquidityList component. I pass LiquidityList an array of type LiquidityPosition[].

Here is my app.tsx:

import React, { useState } from 'react';
import LiquidityList from './components/LiquidityList';
import { LiquidityPosition } from './components/Liquidity'

function App() {
  let positions = [
    {
      time: new Date(2018, 11, 24, 10, 33, 30, 0),
      sizeA: 2,
      sizeB: 1
    }
  ]
  return (
    <>
      <LiquidityList {...positions}/>
    </>
  )
}

export default App;

LiquidityList.tsx:

import React from 'react'
import { LiquidityPosition } from './Liquidity';
import Liquidity from './Liquidity';

export default function LiquidityList(posList: LiquidityPosition[]) {
  return (
    <>
      {
        posList.map(pos => <Liquidity {...pos}/>)
      }
    </>
  )
}

For some reason here, posList is not an array, since it doesn't have a .map method? The error message:

TypeError: posList.map is not a function

CodePudding user response:

The argument provided to a component is an object, each of whose properties corresponds to a prop passed down by the parent. For example, passing down

foo={5}

results in the component's argument being equivalent to

{
  foo: 5
}

The component argument shouldn't be an array - it should be an object containing the one positions prop. Take the individual prop out of the object to get to the array.

In the parent:

<LiquidityList {...{positions}}/>

or

<LiquidityList positions={positions} />

In the child, if you want to pass down pos as the prop:

export default function LiquidityList({ positions }: { positions: LiquidityPosition[] }) {
  return positions.map(pos => <Liquidity pos={pos}/>);
}
  • Related