TIL

제품 이미지 주소가 담긴 배열 요소 받아오기

nana-log 2023. 8. 16. 14:44

처음에 적용한 방법

{props.data?.fetchUseditems.map((product, i) => (
             {product.images[0] ? (
                  <S.Img
                    src={`https://storage.googleapis.com/${product.images[0]}`}
                  ></S.Img>
                ) : product.images[1] ? (
                  <S.Img
                    src={`https://storage.googleapis.com/${product.images[1]}`}
                  ></S.Img>
                ) : product.images[2] ? (
                  <S.Img
                    src={`https://storage.googleapis.com/${product.images[2]}`}
                  ></S.Img>
                ) : (
                  <div
                    style={{
                      width: "200px",
                      height: "200px",
                      backgroundColor: "#eee",
                    }}
                  ></div>
                  
                  .
                  .

find함수를 새까맣게 잊어버리고 있었다....🫠

개선

find 함수를 사용하여 제품 이미지 배열에서 truthy 한 값을 찾아 URL 구성에 사용한다.

{props.data?.fetchUseditems.map((product, i) => (
                {product.images.length ? (
                  <S.Img
                    src={`https://storage.googleapis.com/${product.images.find(
                      (img) => img
                    )}`}
                  />
                ) : (
                  <div
                    style={{
                      width: "200px",
                      height: "200px",
                      backgroundColor: "#eee",
                    }}
                  ></div>
                  
                  .
                  .

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

 

Array.prototype.find() - JavaScript | MDN

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.

developer.mozilla.org