ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 리액트 withRouter를 활용한 현재 페이지 인식
    React 2019. 11. 11. 07:30

    withRouter

    • withRouter 로 컴포넌트를 감싸면 컴포넌트에 props안에 history,location등등의 오브젝트들이잇어서 이놈들을 이용해서 앞페이지 뒷페이지 왔다갔다 할수있음

    • 현재 어떤 페이지에 있는지 체크할수있게됨

    • 언제나 current = true임

      • <Item current={pathname === "/"}>
    import React from "react";
    import { Link, withRouter } from "react-router-dom";
    import styled from "styled-components";
    
    // withRouter덕분에 어떤 컴포넌트와도 연결할 수 있게됨
    
    const Header = styled.header`
      color: white;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 50px;
      display: flex;
      align-items: center;
      padding: 0px 10px;
      background-color: rgba(20, 20, 20, 0.8);
      z-index: 10;
      box-shadow: 0px 1px 5px 2px rgba(0, 0, 0, 0.8);
    `;
    
    const List = styled.ul`
      display: flex;
    `;
    
    const Item = styled.li`
      width: 50px;
      height: 50px;
      text-align: center;
      border-bottom: 3px solid ${props =>
          props.current ? "#3498db" : "transparent"};
      transition: border-bottom 0.5s ease-in-out;
    `;
    
    const SLink = styled(Link)`
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
    `;
    
    // const HeaderC = props => (
    //   <Header>
    //     {console.log(props)} => props정보가 나옴
    //     <List>
    //       <Item current={false}>
    //         <SLink to="/">Movies</SLink>
    //       </Item>
    //       <Item current={true}>
    //         <SLink to="/tv">TV</SLink>
    //       </Item>
    //       <Item current={false}>
    //         <SLink to="/search">Search</SLink>
    //       </Item>
    //     </List>
    //   </Header>
    // );
    
    // export default withRouter(HeaderC);
    
    // 위의 코드는 아래 코드의 다른버전임
    
    export default withRouter(({ location: { pathname } }) => (
      <Header>
        <List>
          <Item current={pathname === "/"}>
            <SLink to="/">Movies</SLink>
          </Item>
          <Item current={pathname === "/tv"}>
            <SLink to="/tv">TV</SLink>
          </Item>
          <Item current={pathname === "/search"}>
            <SLink to="/search">Search</SLink>
          </Item>
        </List>
      </Header>
    ));

    'React' 카테고리의 다른 글

    # 4 Movie DB API 를 활용한 Axios  (0) 2019.11.11
    GlobalStyles  (0) 2019.11.11
    리액트 withRouter를 활용한 현재 페이지 인식  (0) 2019.11.09
    React에서 CSS 작업  (0) 2019.11.09
    리액트 라우터 2부  (0) 2019.11.09

    댓글

Designed by Tistory.