How Use images from javascript array in react using filter and map function

跟風遠走 提交于 2021-02-10 14:23:03

问题


I have a javascript array like this:

const IMGS = [{
    id: 0,
    path: "../img/a1.jpeg",
  },
  {
    id: 1,
    path: "../img/a1-01.jpeg",
  },
  {
    id: 2,
    path: "../img/a1-02.jpeg",
  },
  {
    id: 3,
    path: "../img/a1-03.jpeg",
  }
]
export default IMGS;

There are more images I am just showing few of them, I need to show all the images in react from this array. The condition is the image_id should be >=18 but <30. How can I achieve that? (I need to know the syntax).

I know I can do it using filter or map function, actually I'm new to javascript coming from c++, python background. It looks bit confusing to me. Please help! This is my react code where I'm rendering it

<React.Fragment>
      <Jumbotron>
          <img src={background} alt="Not loading"  id="jumbotron-image" className="img-fluid"/>
      </Jumbotron>
      <div className="container">
          <div className="row">
              <h1>Trending</h1>
          </div>
          <div className="row">
            {/*images go here*/}
          </div>
      </div>
  </React.Fragment>

回答1:


 const IMGS = [
      {
        id: 0,
        src:require("../img/a1.jpeg"),
      },
      {
        id: 1,
        src: require("../img/a1.jpeg"),
      },
      {
        id: 2,
        src:require("../img/a1.jpeg"),
      },
      {
        id: 20,
        src:require("../img/a1.jpeg"),
      },
    ]
    const imgFilter= IMGS.filter((img) => img.id >= 18 && img.id < 30)

     {imgFilter.map(p => {
          return <img key={p.id} src={p.src} />;
        })}



回答2:


Use filter

const IMGS = [
  {
    id: 0,
    path: "../img/a1.jpeg",
  },
  {
    id: 1,
    path: "../img/a1-01.jpeg",
  },
  {
    id: 2,
    path: "../img/a1-02.jpeg",
  },
  {
    id: 20,
    path: "../img/a1-03.jpeg",
  },
]

const res = IMGS.filter((img) => img.id >= 18 && img.id < 30)

console.log(res)


来源:https://stackoverflow.com/questions/64204355/how-use-images-from-javascript-array-in-react-using-filter-and-map-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!