티스토리 뷰
// 사이드바 만들기 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/
'개발공부 > React' 카테고리의 다른 글
#React 이미지 경로 문제 (0) | 2024.05.17 |
---|---|
React_정렬, 검색 기능 만들기 (0) | 2023.09.10 |
React_삼항연산자, 배열의 객체의 속성에 접근하기 (0) | 2023.09.07 |
React_하위 컴포넌트로 props가 전달되는 과정 (0) | 2023.09.07 |
React_setState : 원본데이터 변경하지 말고 새로운 배열을 생성하자 (0) | 2023.09.06 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 프로토타입 체이닝
- 머리아프다..
- 에이블스쿨2일차
- unique "key" prop.
- 대괄호표기법
- .then()
- 태스크큐
- universal rendering
- JSX
- 상속
- 조대곤교수님
- 미들웨어위치
- 객체리터럴
- 함수형코딩
- .finally()
- 전역변수
- .catch()
- 동등비교연산자
- 함수
- 비동기
- react
- 배열내특정요소찾기
- 객체속성 추가 삭제
- promise
- 리액트 이미지경로
- null과 undefined
- Props
- unexpected character
- cors위치
- 문자열
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함