[React] 조건부 렌더링

SuJeong·2022년 11월 20일
0

React

목록 보기
9/9

1. 컴포넌트 분리

코드의 가독성과 유지보수성을 향상시켜 코드 퀄리티를 올리기 위해 컴포넌트 분리를 적용

  • view와 로직을 분리
  • state에 따라서 분리
    가독성이 떨어지지 않는지 재사용 될 수 있는지에 초점!

2. 조건부렌더링 구현

import Brand from './Brand/Brand';
import Price from './Price/Price';

const TABS = [
    {
      id: 0,
      title: '브랜드',
      content: (
        <Brand
          setSelectedAllFilter={setSelectedFilter}
          selectedFilter={selectedBrand}
        />
      ),
    },
    {
      id: 1,
      title: '가격',
      content: (
        <Price
          setSelectedAllFilter={setSelectedFilter}
          selectedFilter={selectedPrice}
        />
      ),
    },
  ];
<div className="left-filter">
              <ul className="filter-list">
                {TABS.map(filter => {
                  const isCurrent = currentTab === filter.id;

                  return (
                    <li key={filter.id}>
                      <button
                        onClick={() =>
                          setCurrentTab(isCurrent ? '' : filter.id)
                        }
                        className={isCurrent ? 'current' : ''}
                      >
                        {filter.title}
                      </button>
                    </li>
                  );
                })}
              </ul>
            </div>
{TABS.find(({ id }) => id === currentTab)?.content}
  1. 해당 버튼을 클릭했을 때 그것에 맞는 panel을 보여준다.
  2. panel에 보여줄 화면을 컴포넌트화 시킨다.
  3. 탭을 눌렀을 때 변경되는 currentId값에 따라 컴포넌트가 보여질 수 있도록 객체에 컴포넌트를 할당하고 객체가 조건문의 역할을 수행할 수 있도록 구현한다.
profile
Front-End Developer

0개의 댓글