Frontend/React

[React] + [Typescript + Emotion]에서 props 넘기는 방법

rachel_13 2022. 9. 10. 22:10

체크박스를 커스텀하는 과정에서, 체크박스의 상태에 따라 보여지는 스타일이 달라져야 하기 때문에,

props로 체크박스의 상태를 넘겨줘야 했다.

 

필자는 CRA with Typescript Template에 Emotion을 적용해서 개발 중에 있었음.

 

React + style-component 사용할 때 처럼 그냥 props로 넘겨주면 오류가 남

 

(변경 전)

  • index.tsx
const [checked] = useState(false)

<div css={styles.checkBoxStyle}>
	<label htmlFor="checkbox" />
        <input
          type="checkbox"
          id="checkbox"
          checked={checked}
        />
    </label>
</div>
  • style.ts
export const checkBoxStyle = css`
 background: ${(props) => props.checked ? `url(${active}) no-repeat 100%/contain` : "#ffff"};
`;

 

(변경 후)

 

👉 방법 : style.ts에서 넘겨주는 props에 대한 Type 설정이 필요함.

  • index.tsx
const [checked, setChecked] = useState(false);

<div css={styles.checkBoxStyle({ checked })}>
	<label htmlFor="checkbox" />
		<input type="checkbox" id="checkbox"
        onChange={(): void => setChecked(!checked)}
	/>
</div>

- checkBoxStyle 안에 checked를 props로 넘겨주고 있다.

+) 사실 input type="checkbox"의 특징을 살려서 checked 속성을 활용하고 싶었는데,

checked의 상태를 state로 관리하고, 이벤트가 있을 때마다, 이 상태가 변경이 되어야 해서 onChange로 구현하게 되었다. 

  • style.ts
type CheckedProps = {
  checked: boolean;
};

export const checkBoxStyle = (props: CheckedProps) => css`
	background: ${props.checked
      ? `url(${active}) no-repeat 100%/contain`
      : "#ffff"};
  }

 

[참고]

어떤 센세의 좋은 글 : https://namunamu1105.medium.com/react-js-typescript-emotion-js-%EC%A1%B0%ED%95%A9%EC%97%90%EC%84%9C-emotion-js%EC%97%90-props%EB%84%98%EA%B8%B0%EB%8A%94-%EB%B2%95-5e1ab7a33f8c

 

 

 

'Frontend > React' 카테고리의 다른 글

pnpm cache clean  (0) 2023.03.02
Typescript - useRef() 사용시 type 설정  (0) 2022.12.13
[Redux]미들웨어(middleware)  (0) 2022.08.14
[Redux] 관심사의 분리(SoC)  (0) 2022.08.14
[Redux] 리덕스 원리 이해하기  (0) 2022.08.13