본문 바로가기
> 메모/GitHub

[깃] 이미지 폴더 생성한거 활용

by 자몽주스 2024. 9. 8.
728x90
참고할 글

[깃] 이미지 폴더 생성하고 이미지 넣기 (tistory.com)

 

[깃] 이미지 폴더 생성하고 이미지 넣기

이미지 폴더에서 이미지 넣기업로드 클릭이미지 파일 끌어서 업로드 하기녹색버튼 클릭잘 생성된거 확인

jamongsoda.tistory.com


이렇게 fingers 폴더 업로드 한거 활용하기

이렇게 이미지들 들어가 있음.


1. 이미지 URL 확인하기

GitHub Pages를 통해 정적 파일을 제공할 때, 이미지 URL은 다음과 같은 형식입니다:

https://username.github.io/repository-name/nff_product/fingers/ring1.jpg

여기서 username은 GitHub 사용자명, repository-name은 저장소 이름입니다.

 

이미지 URL은 다음과 같습니다:

https://kku-git.github.io/nff_product/fingers/ring1.jpg

2. JSON 파일에 이미지 URL 포함하기

이미지 URL을 JSON 데이터에 포함시켜야 합니다. 예를 들어, data.json 파일을 다음과 같이 업데이트합니다:

[
  { "id": 1, "title": "Ring 1", "price": "$10", "image": "https://johnsmith.github.io/my-project/nff_product/fingers/ring1.jpg" },
  { "id": 2, "title": "Ring 2", "price": "$15", "image": "https://johnsmith.github.io/my-project/nff_product/fingers/ring2.jpg" },
  { "id": 3, "title": "Ring 3", "price": "$20", "image": "https://johnsmith.github.io/my-project/nff_product/fingers/ring3.jpg" },
  ...
  { "id": 20, "title": "Ring 20", "price": "$200", "image": "https://johnsmith.github.io/my-project/nff_product/fingers/ring20.jpg" }
]

3. React에서 이미지 사용하기

이미지 URL이 포함된 JSON 데이터를 불러와서 이미지와 데이터를 렌더링하는 React 컴포넌트를 작성합니다.

예시 React 컴포넌트

import React, { useState, useEffect } from 'react';

function ItemList() {
  const [data, setData] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const ITEMS_PER_PAGE = 9;

  // JSON 데이터 불러오기
  useEffect(() => {
    fetch('https://johnsmith.github.io/my-project/data.json')  // GitHub Pages에서 JSON 데이터 가져옴
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error('Error fetching data:', error));
  }, []);

  // 페이지에 해당하는 항목을 계산
  const indexOfLastItem = currentPage * ITEMS_PER_PAGE;
  const indexOfFirstItem = indexOfLastItem - ITEMS_PER_PAGE;
  const currentItems = data.slice(indexOfFirstItem, indexOfLastItem);

  const totalPages = Math.ceil(data.length / ITEMS_PER_PAGE);

  // 페이지 변경 함수
  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  return (
    <div>
      <div className="item-container">
        {currentItems.map(item => (
          <div key={item.id} className="item">
            <div className="overlay-wrap">
              <div className="overlay">
                <p>{item.title}</p>
                <p>{item.price}</p>
              </div>
            </div>
            <img src={item.image} alt={item.title} /> {/* 이미지 렌더링 */}
          </div>
        ))}
      </div>
      <Pagination 
        currentPage={currentPage} 
        totalPages={totalPages} 
        onPageChange={handlePageChange} 
      />
    </div>
  );
}

export default ItemList;

4. 주의사항

  • CORS: GitHub Pages에서 제공하는 파일은 CORS 정책에 따라 제한이 없지만,
  • 다른 서버에서 접근할 경우 CORS 문제가 발생할 수 있습니다.
  • 이미지 최적화: 웹에서 이미지를 로드할 때,
  • 이미지 파일의 크기와 포맷을 최적화하여 페이지 로딩 성능을 개선하는 것이 좋습니다.
728x90