For Programmer

3. Landing Page 만들기(1) - 영화사이트 만들기 본문

React & Node.js 프로젝트/영화사이트 만들기

3. Landing Page 만들기(1) - 영화사이트 만들기

유지광이 2020. 7. 28. 20:21
728x90

*이번시간에는 3번까지 할예정이며 4~5번은 다음시간에 할예정이다.

*fetch 통신에대한 사용법은 다음글을 참고하자

https://webisfree.com/2019-05-15/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-fetch-api-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0

 

자바스크립트 fetch API 알아보기

자바스크립트에서 fetch API를 사용하여 서버와 비동기 통신을 어떻게 할 수 있는지 그 방법과 예제에 대하여 자세히 알아봅니다.

webisfree.com

*또한 fetch통신과 Axios통신의 차이점은 fetch통신은 응답을 promise형태로 하기때문에 이를 json형태로 바꿔야한다는점과 에러처리방식에있어서 차이가있다.

1.LandingPage.js를 코드를작성(movie API를 통해 가장인기있는 영화에대한 정보를  fetch통신을 통해 받아온다.) + 메인이미지를 꾸미기위한 데이터까지 넘겨준다.

import React, { useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom';
import { API_URL, API_KEY, IMAGE_BASE_URL } from '../../Config';
import MainImage from './Sections/MainImage';

const LandingPage = (props) => {
  const [Movies, setMovies] = useState([]); //배열로 값을받기 때문
  const [MainMovieImage, setMainMovieImage] = useState(null);

  useEffect(() => {
    const endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`;
    fetch(endpoint)
      .then((response) => response.json()) //응답을 json형태로 변경하여 then의 response에 반환
      .then((response) => {
        console.log(response);
        setMovies([...response.results]); //console로 찍어보면 results배열에 담겨서 데이터보내줌
        //스프레드연산자를 사용하여 배열에 집어넣음
        setMainMovieImage(MainMovieImage || response.results[0]);
        //로딩될때는 MainMovieImage값이 null이기 때문에 response.results[0]값이 들어오며
        //그다음 loding button을 눌릴때마다 MainMovieImage즉 초기이미지로 고정이된다.
        //안그러면 로그창에 오류발생
      });
  }, []);
  return (
    <div style={{ width: '100%', margin: '0' }}>
      {/*Main Image */}
      {MainMovieImage && ( //만약 이러한 작업을 하지않을 경우 React는 MainMovieImage를 state에 넣기전에
        //페이지를 렌더링 할려고 하여 backrop_path가 null 에러가 발생한다.

        /*console.log 보면 backdrop_path에 이미지에대한 이름이 담겨있다.*/
        <MainImage
          image={`${IMAGE_BASE_URL}w1280/${MainMovieImage.backdrop_path}`} //영화이미지
          title={MainMovieImage.original_title} //영화제목
          text={MainMovieImage.overview} //영화에대한설명
        />
      )}

      <div style={{ width: '85%', margin: '1rem auto' }}>
        <h2>Movies by latest</h2>
        <hr />

        {/*Movie Grid Cards */}
        
      </div>

      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <button>Load More</button>
      </div>
    </div>
  );
};

export default withRouter(LandingPage);

2.MainImage.js를 만든다.(client-src-components-views-LandingPage-Sections-MainImage.js)

import React from 'react';

function MainImage(props) {
  return (
    <div
      style={{
        background: `linear-gradient(to bottom,rgba(0,0,0,0)
     39%,rgba(0,0,0,0)
     41%,rgba(0,0,0,0.65)
     100%),
     url(${props.image}), #1c1c1c`,
        height: '500px',
        backgroundSize: '100%,cover',
        backgroundPosition: 'center,center',
        width: '100%',
        position: 'relative',
      }}
    >
      <div>
        <div
          style={{
            position: 'absolute',
            maxWidth: '500px',
            bottom: '2rem',
            marginLeft: '2rem',
          }}
        >
          <h2 style={{ color: 'white' }}> {props.title}</h2>
          <p style={{ color: 'white', fontSize: '1rem' }}>{props.text}</p>
        </div>
      </div>
    </div>
  );
}

export default MainImage;

 

실행결과

해당강의

 

728x90
Comments