.map In React.js


I have this file CarsData.js (content some info)

const CarsData = [
  { id: "car_01",  image: imageToyota,     title: "Toyota",      type: "SUV" },
  { id: "car_02",  image: imageAudi,       title: "Audi",        type: "SUV" },
  { id: "car_03",  image: imageNissan,     title: "Nissan",      type: "CAR" },
  { id: "car_04",  image: imageKia,        title: "Kia",         type: "TRUCK" }

export default CarsData

and I display all the code in this section CardsCars.js

const CardsCars = () => {

  const card = CarsData.map(car => {
    return <CardCar image={car.image} title={car.title} type={car.type}/>

  return (
    <div className='row'>

        {card} //display all the info in CarsData


export default CardsCars

How can I display only 2 info from CarsData.js (not 4 info)

>Solution :

You can use the "slice()" method which returns selected elements in an array, as a new array. Then You can run "map()" to show the data.

CarsData.slice(0,2).map((car) => (<CardCar image={car.image} title={car.title} type={car.type}/>));

In this case, the first 2 info will be displayed.

Leave a ReplyCancel reply