프로필 페이지에서 게시글을 리스트, 갤러리 두가지 뷰로 보여주는 것을 구현하기 위해 탭 버튼을 구현하는 것을 공부해 적용했다.
•
탭 인덱스를 관리하기 위해 useState Hook을 생성한다.
export function PostsContainer() {
const [activeIndex, setActiveIndex] = useState(0);
,,,
return (
);
}
JavaScript
복사
•
tabs에는 탭 컴포넌트와 해당 탭이 활성화 되었을 때 보여줄 컴포넌트를 갖는 객체로 이루어진 배열을 할당한다. activeIndex의 상태값을 클릭한 탭의 인덱스로 변경한다. 이는 해당 탭이 활성화되었다는 것을 의미한다.
export function PostsContainer() {
const [activeIndex, setActiveIndex] = useState(0);
const post = [
{
id: '61efc0c6924ed2392e3d019d',
content: 'sdfsfsdfsdfsdf',
image: 'http://146.56.183.55:5050 /imgurl',
createdAt: '2022-01-25T09:20:06.388Z',
updatedAt: '2022-01-28T14:55:25.309Z',
hearted: false,
heartCount: 1,
comments: [],
commentCount: 0,
author: {
_id: '61ef2a93368570e1514706dc',
username: '빵쟁이',
accountname: 'bread_fit',
intro: '빵',
image: 'http://146.56.183.55:5050/1643063923723.png',
isfollow: false,
following: ['61ef3eba368570e1514821c8', '61ef30b2368570e1514708e0', '61ef37bd368570e1514709d5'],
follower: [
'61ef30b2368570e1514708e0',
'61ef37bd368570e1514709d5',
'61ef3eba368570e1514821c8',
'61ef40f3368570e15148254d',
'61ef40fd368570e151482560',
],
followerCount: 45,
followingCount: 3,
},
}];
const tabs = [
{
tabComponent: (
<S.TabItem key='tab-0'>
<S.TabButton onClick={() => setActiveIndex(0)}>
{activeIndex === 0 ? <PostListIconOn /> : <PostListIconOff />}
</S.TabButton>
</S.TabItem>
),
tabContent: <PostList post={post} />,
},
{
tabComponent: (
<S.TabItem key='tab-1'>
<S.TabButton onClick={() => setActiveIndex(1)}>
{activeIndex === 1 ? <PostGalleryIconOn /> : <PostGalleryIconOff />}
</S.TabButton>
</S.TabItem>
),
tabContent: <PostGallery post={post} />,
},
];
return (
,,,
);
}
JavaScript
복사
•
activeIndex 값이 바뀔때마다 tabs의 activeIndex 번째 객체의 tabContent 컴포넌트가 렌더링된다.
export function PostsContainer() {
const [activeIndex, setActiveIndex] = useState(0);
,,,
const tabs = [
{
tabComponent: (
<S.TabItem key='tab-0'>
<S.TabButton onClick={() => setActiveIndex(0)}>
{activeIndex === 0 ? <PostListIconOn /> : <PostListIconOff />}
</S.TabButton>
</S.TabItem>
),
tabContent: <PostList post={post} />,
},
{
tabComponent: (
<S.TabItem key='tab-1'>
<S.TabButton onClick={() => setActiveIndex(1)}>
{activeIndex === 1 ? <PostGalleryIconOn /> : <PostGalleryIconOff />}
</S.TabButton>
</S.TabItem>
),
tabContent: <PostGallery post={post} />,
},
];
return (
<>
{post.length === 0 || (
<S.Container>
<S.TabContainer>
<S.TabList>{tabs.map((tab, index) => tab.tabComponent)}</S.TabList>
</S.TabContainer>
{tabs[activeIndex].tabContent}
</S.Container>
)}
</>
);
}
JavaScript
복사