티스토리 뷰

// 사이드바 만들기 App.js

import './App.css'
import React, { Component } from "react";
import Sidebar from "./Sidebar";
import Button from './components/Button';
const menus = [ // 메뉴데이터
  {
    icon: '♜',
    title: 'HOME'
  },
  {
    icon: '♞',
    title: 'ABOUT'
  },
  {
    icon: '☻',
    title: 'SETTING'
  },
  {
    icon: '♜',
    title: 'HOME'
  },
  {
    icon: '♞',
    title: 'ABOUT'
  },
  {
    icon: '☻',
    title: 'SETTING'
  }
]

class App extends Component{
  state = {
    toggle: false
  }
  toggleMenu = () =>{
    this.setState({toggle : !this.state.toggle})
  }
  render(){
    const { toggle } = this.state

    return(
      <div className='App'>
        <Button handleClick={this.toggleMenu}>사이드바 열기/닫기</Button>
        <Sidebar open={toggle}>                                                                         // open 이름은 자유롭게 설정이 가능하다
          {menus.map((menu, id)=>{
            return<div className='menu' key={id}>{menu.icon} {menu.title}</div>
          })}
        </Sidebar>
      </div>      
    )
  }
 
  }


export default App
// Sidebar.js 컴포넌트
 
import './Sidebar.css'

function Sidebar({open, children}){  // open은 App.js에서 props로 내려온 것, open의 실제내용은 toggle의 true / false 값이다
    return(
        <div className={`sidebar ${open ? 'open' : ''}`}> // open의 실제내용은 toggle의 true / false 값이다, toggle이 true                                                                                              이면 open 클래스 설정, false이면 클래스 이름 없음
            <div className='sidebar-menus'>{children}</div>
        </div>
    )
}

export default Sidebar
// Sidebar.css
 
.sidebar{
    width: 30%;
    height: 100vh;
    background: khaki;
    position: absolute;
    left: -30%;                                               // 처음에 -30%로 안보이게 설정해놓는다
    top: 0;
    transition:  all 0.7s ease-out;
}
.open{
    left: 0;            // 사이드바 열기를 클릭하면 open 클래스가 설정되면서 left: -30% -> 0 으로 되면서 사이드바가 나타난다
}
.sidebar-menus{
    width: 100%;
    height: 100%;

    display: flex;
    flex-direction: column;
}

정리

1. 하위 컴포넌트로 props값 전달시 변수이름(?)은 자유롭게 설정이 가능하다, state이름은 변경불가.

2. 하위 컴포넌트에 자유롭게 설정된 변수가 props로 들어왔을 때 그 내용물은 state의 값이다.

3. 사이드바 display:none -> block 말고 left : -30%로 좌측에 숨어져있다가 0으로 되면서 나오는 것도 좋은거 같다.

 

코드출처

선생님 블로그 : https://syleemomo.tistory.com/