Today I Learned 2023.03.08. [React 프로젝트 3]

Dongchan Alex Kim·2023년 3월 8일
0

Today I Learned

목록 보기
6/31
post-thumbnail

문제상황

컴포넌트 분리에 감이 좀 안잡혀서 힘들었던 것 같다.
각 해당되는 styled-component에 대해 각 컴포넌트를 연결해주는 작업이 참 힘들었던 것 같다.

해결

const BasicButton= ({ children, ...theme}) =>{
    return <StButton theme={Object.keys(theme)[0]} onClick = {theme.onClick}>{children}</StButton>
}

const StButton = styled.button`
    border-radius: 8px;
    width: 200px;
    height: 50px;
    border: 3px solid #15de9b;
    background-color: transparent;
    ${({theme}) => {
    switch (theme) {
      case 'LargePrime':
        return css`
          cursor : pointer;
          font-Weight : bold;
        `
      case 'LargeNegative':
        return css`
          cursor : pointer;
          font-Weight : bold;
          color : #cf0606;
          border : 3px solid #f29c9c;
        `
      case 'NormalMedium':
        return css`
          cursor : pointer;
          background-color: #15de9b;
          width : 130px;
          height: 45px;
          :active{
            background-color: #178a69;
          }
        `
      case 'NormalSmall':
        return css`
          cursor : pointer;
          background-color: #15de9b;
          width : 100px;
          height: 40px;
          :active{
            background-color: #178a69;
          }
        `
      case 'NegativeMedium':
        return css`
          cursor : pointer;
          background-color: #f29c9c;
          border : 3px solid #f29c9c;
          width : 130px;
          height: 45px;
          :active{
            background-color: #a52121;
          }
        `
      case 'NegativeSmall':
        return css`
          cursor : pointer;
          background-color: #f29c9c;
          border : 3px solid #f29c9c;
          width : 100px;
          height: 40px;
          :active{
            background-color: #a52121;
          }
        `
    }
  }}
`

일단 버튼 컴포넌트를 따로 하나 빼준다.
기본 베이스로 되는 컴포넌트를 받아서, 이 컴포넌트에 children을 넘기는 방식을 고민해보자.

<BasicButton LargePrime onClick ={()=>{alert('버튼을 클릭하셨습니다')}}>Large Prime Button <TfiAngleRight/></BasicButton>

이런 식으로 가져올 수 있는데,
LargePrime 이런식으로 children props로 데리고 올 수 있었다.
위에 보면, { children, ...theme} 으로 보낸 프롭스를 받아서 콘솔 찍어보면서 형변환을 시도했고, 해결이 되었다.

switch/case문보다 사실(조건문에 대한 연산) props를 객체로 받아와서 하는 방식을 조금 더 선호한다고 들었는데,
한번 나중에 시도해보아야겠다.

<참고 자료>
https://www.daleseo.com/react-button-component/

profile
Disciplined, Be systemic

0개의 댓글