웹/프론트엔드

[React/Typescript] CSS Property를 Props로 사용하는 법

이민훈 2022. 8. 22. 02:49

컴포넌트를 만들 때, CSS Property 값을 Props로 받고 싶을 때가 있다.

style 자체를 넘겨받고 싶을 땐, React에서 제공해주는 React.CSSProperties 타입을 사용하면 된다.

 

interface TestProps {
  style: React.CSSProperties;
}

const Test = (props: TestProps) => {
  return <div style={props.style} />;
};

export default Test;

 

하지만 css property 중 하나의 값을 프롭으로 받고 싶다면 어떻게 해야 할까?

csstype 모듈에서 StandardProperties를 import해서 원하는 css property를 키값으로 넣어주면 된다.

 

import type { Properties } from "csstype";

interface TestProps {
  display: Properties["display"];
}

const Test = (props: TestProps) => {
  return <div style={{ display: props.display }} />;
};

export default Test;

 

만약 모든 css property 들을 프롭으로 받고 싶다면? 아래처럼 하면 된다.

 

import type { Properties } from "csstype";

type CSSProperties = {
  [key in keyof Properties]: Properties[key];
};

interface TestProps extends CSSProperties {}

const Test = (props: TestProps) => {
  return <div style={{...props}} />;
};

export default Test;

 

아래처럼 css property를 프롭으로 넘길 수 있게 된다.

 

정상적으로 넘길 props들이 목록으로 뜨는 모습
해당 프롭에 넘길 수 있는 값들이 뜨는 모습

 

참고 : https://use-form.netlify.app/modules/_node_modules_csstype_index_d_.html

 

"node_modules/csstype/index.d" | typescript

 

use-form.netlify.app