ABOUT ME

1st. CES 2nd. GBT

Today
Yesterday
Total
  • React JS_Router 2
    WEB/ReactJS 2020. 1. 27. 16:23

    #6.2 ~ 6.3

    아래 강의 중 'ReacJS로 웹 서비스 만들기'를 보고 배운 것과 모르는 것을 찾아 정리한 내용입니다.

    https://academy.nomadcoders.co/courses

     

    Academy

    % Complete

    academy.nomadcoders.co

     

     

    1. 네비게이션 사용하기

    /와 /about을 navigate 하기위해서는 네비게이션을 사용해야 한다. Navigation.js 파일에 네비게이션 컴포넌트를 다음과 같이 만든다. 코드 상의 Home, About 각각은 페이지에 대한 목록이라고 볼 수 있다.

    //src/components/Navigation.js
    import React from 'react';
    import './Navigation.css';
    
    function Navigation() {
        return (
            <div>
                <a href="/">Home</a>
                <a href="/about">About</a>
            </div>
        );
    }
    
    export default Navigation;

    위 코드를 실행하면 About 컴포넌트가 제대로 작동하지 않을 것이다. <a href=""></a> 코드는 html 코드이기 때문이다. 이게 무슨 말인가. html은 다른 페이지로 이동할 때 모든 페이지를 새로고침한다. 리액트로 만든 페이지에서 원치 않는 동작이다. 

     

    따라서  a와 href 대신, 리액트 라우터에 있는 Link 컴포넌트와 to를 사용할 것이다. 이렇게 하면 About이 빠르게 화면에 나타나는 것을 볼 수 있다. 단, 주의할 것은 Link는 Router 안에 있어야 한다는 것이다. Router 밖에서 Link를 사용할 수 없다(line2).

    //src/components/Navigation.js
    import React from 'react';
    import { Link } from 'react-router-dom';
    import './Navigation.css';
    
    function Navigation() {
        return (
            <div>
                <Link to="/">Home</Link>
                <Link to="/about">About</Link>
            </div>
        );
    }
    
    export default Navigation;

     

     

    2. 라우터 간 props 공유하기

    Home과 About 사이에서 영화의 정보(props)를 공유하여 Home에 있는 영화를 클릭하면 About으로 넘어가 클릭한 영화의 정보를 보여주도록 만들고 싶다. 이를 위해 스크린(라우터) 사이에서 정보를 공유하는 방법을 알아볼 것이다.

     

    모든 컴포넌트에는 props가 있다. 라우터로 설정한 컴포넌트(Home, About)도 props를 가진다. 콘솔창에 About의 props를 출력해보면 다음과 같은 것들이 보인다.

    router props

    이는 react-router에 의해 전달받은 props있다.

    history를 통해 다른 경로로 이동하거나 앞, 뒤 페이지로 전환할 수 있다.

    loaction은 현재 경로와 URL 쿼리(/about?foo=bar 형식)에 대한 정보를 가지고 있다.

    match는 어떤 라우트에 매칭 되는지에 대한 정보와 params(/about/:name 형식) 정보를 가지고 있다.

     

    지금은 이 props가 무엇인지 보다 이를 사용할 수 있다는 것에 집중해야 한다. 우리는 Link를 통해 About 페이지에 props(영화정보)를 보낼 것이다. Link 공식 문서에 의하면 to는 객체로 설정이 가능하므로, 영화정보를 객체로 담아 About에 보낼 것이다.

     

    About에 대한 Link의 to를 객체로 설정한다. 이 링크를 클릭하면 리액트 라우터는 pathname인 /about으로 가고, 그 페이지는 컴포넌트 About이 될 것이다. 또한, route로 state(fromNavigation)를 보내고 있다. 이렇게 보낸 정보를 About 컴포넌트에서 받아서 사용할 수 있는 것이다.

     

    //src/components/Navigation.js
    import React from 'react';
    import { Link } from 'react-router-dom';
    import './Navigation.css';
    
    function Navigation() {
        return (
            <div className="nav">
                <Link to="/">Home</Link>
                <Link to={{
                	pathname: "/about",
                    state: {
                        fromNavigation: true
                    }
                }}
                >
                About
                </Link>
            </div>
        );
    }
    
    export default Navigation;

     

    처음 목표인 Home에 있는 영화를 클릭하면 다른 페이지(About이 아닌 Detail 라우트를 새로 만들 것이다)로 넘어가 클릭한 영화의 정보를 보여주기 위해서는 Movie.js 에서 Link를 사용해서 정보를 전달하고, Detail.js 에서 이를 받아서 사용하면 된다.

    //src/components/Movie.js
    import React from 'react';
    import { Link } from 'react-router-dom';
    import PropTypes from 'prop-types';
    import './Movie.css'
    
    function Movie({ id, year, title, summary, poster, genres }) {
        return (
          <div className="movie">
            <Link
              to={{
                pathname: `/movie/${id}`,
                state: {
                  year,
                  title,
                  summary,
                  poster,
                  genres
                }
              }}
            >
              <img src={poster} alt={title} title={title} />
              <div className="movie__data">
                <h3 className="movie__title">{title}</h3>
                <h5 className="movie__year">{year}</h5>
                <ul className="movie__genres">
                  {genres.map((genre, index) => (
                    <li key={index} className="genres__genre">
                      {genre}
                    </li>
                  ))}
                </ul>
                <p className="movie__summary">{summary.slice(0, 180)}...</p>
              </div>
            </Link>
          </div>
        );
      }
    
    Movie.prototype = {
        id: PropTypes.number.isRequired,
        year: PropTypes.number.isRequired,
        title: PropTypes.string.isRequired,
        summary: PropTypes.string.isRequired,
        poster: PropTypes.string.isRequired,
        genres: PropTypes.arrayOf(PropTypes.string).isRequired
    };
    
    export default Movie;
    //src/routes/Detail.js
    import React from 'react';
    
    class Detail extends React.Component{
        render() {
            const {location} = this.props;
            return <span>{location.state.title}</span>
        }
    }
    
    export default Detail;

     

     

    #Reference

    라우트 파라미터: https://velopert.com/3417

    'WEB > ReactJS' 카테고리의 다른 글

    React JS_Redirecting  (0) 2020.01.29
    React JS_Router 1  (0) 2020.01.27
    React JS_웹 페이지 클라우드에 올리기 by Github  (0) 2020.01.26
    React JS_Axios  (0) 2020.01.22
    React JS_State  (0) 2020.01.20

    댓글

Designed by Tistory.