Search code examples
javascriptreactjstypescriptreact-pdf

Map function, set index from and index to


Is it possible set index of function/method map()? Do not render all cars, but cars e.g. from id 2 to id 4. Example with 5 cars and render with component <View> and <Text> from library "@react-pdf/renderer": "2.3.0".

{
  "cars": [
    {
      "id": "0",
      "brand": "Toyota",
      "type": "Corolla",
      "color": "white"
    },
    {
      "id": "1",
      "brand": "Mazda",
      "type": "CX-30",
      "color": "red"
    },
    {
      "id": "2",
      "brand": "Honda",
      "type": "Civic",
      "color": "brown"
    },
    {
      "id": "3",
      "brand": "Audi",
      "type": "A6",
      "color": "black"
    },
    {
      "id": "4",
      "brand": "Mercedes",
      "type": "GLC",
      "color": "grey"
    }
  ],
  "total": 5
}

{data?.cars.map((car: any, index: number) => {
  return (
    <View 
      key={index}
    >
      <Text>{index + 1}</Text>
      <Text>{car.brand || ""}</Text>
      <Text>{car.type || ""}</Text>
      <Text>{car.color || ""}</Text>
    </View>
  )
}

With for loop is not works.

{(() => {
  return (
    for (let j = 2; j < 5; j++) {  // <--- Unreachable code
      <View 
        key={j}
      >
        <Text>{j + 1}</Text>
        <Text>{car.brand || ""}</Text>
        <Text>{car.type || ""}</Text>
        <Text>{car.color || ""}</Text>
      </View>
    }
  )
})()}

I use typescript and reactjs 17.0.2.


Solution

  • You can use slice method, data?.cars.slice(2).map to slice the array from index 3 ( the element whose has id = 2 ) to the rest of the array ( as the element whose id = 4 is the last element in the array ).

    {data?.cars.slice(2).map((car: any, index: number) => {
      return (
        <View 
          key={index}
        >
          <Text>{car?.brand : ""}</Text>
          <Text>{car?.type : ""}</Text>
          <Text>{car?.color : ""}</Text>
        </View>
      )
    }