React/공부공부
[React] Styled-Components 참고 (props warning / Transient Props)
phyho
2024. 9. 25. 11:41
* 비표준 props가 DOM에 전달되는 경우
버튼을 누르면 isVisible 상태값이 변경되며 Box 컴포넌트가 나타나고 사라지는 css 스타일을 적용.
const App = () => {
const [isVisible, setIsVisible] = useState(true);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>Toggle Box</button>
<Box visible={isVisible} />
</div>
);
};
const Box = styled.div`
background-color: lightblue;
width: 200px;
height: 200px;
display: ${(props) => (props.visible ? 'block' : 'none')}; // 경고 발생
`;
콘솔창에 경고가 뜬다.
console.js:288 styled-components: it looks like an unknown prop "visible" is being sent through to the DOM, which will likely trigger a React console error. If you would like automatic filtering of unknown props, you can opt-into that behavior via <StyleSheetManager shouldForwardProp={...}> (connect an API like @emotion/is-prop-valid) or consider using transient props ($ prefix for automatic filtering.)
=> "visible" 이라는 비표준 속성이 DOM 요소로 전달되었기 때문.
$ Prefix 를 사용하라고 조언하고 있다.
( Transient Props ($ Prefix) 사용 )
const App = () => {
const [isVisible, setIsVisible] = useState(true);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>Toggle Box</button>
<Box $visible={isVisible} /> // $visible 사용
</div>
);
};
const Box = styled.div`
background-color: lightblue;
width: 200px;
height: 200px;
display: ${(props) => (props.$visible ? 'block' : 'none')}; // $ 사용, 경고 없음
`;
$ 로 시작하는 Transient Props는 해당 속성값이 DOM으로 전달되지 않아 스타일링에만 사용.