본문으로 바로가기
728x90

Problem

import styled from 'styled-components';

export interface TextDivProps {
  color?: string;
  size?: number;
  weight?: number;
  nowrap?: boolean;
}

export const TextDiv = styled.div<TextDivProps>`
  color: ${({ color }) => (color ? color : 'black')};
  font-size: ${({ size }) => (size ? size : 14)}px;
  font-weight: ${({ weight }) => (weight ? weight : 400)};
  white-space: ${({ nowrap }) => (nowrap ? 'nowrap' : 'normal')};
`;

 

Why warning is appeared?

Basically HTML symentic tag includes variety of props such as width, height, id and etc and those standard property should be passed in string. So non-boolean attribute warnning goes up when boolean type of property is given.

# styled-components documentation

If the styled target is a simple element (e.g. styled.div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props.
Note how the inputColor prop is not passed to the DOM, but type and defaultValue are. That is styled-components being smart enough to filter non-standard attributes automatically for you.

 

Solution

1. Replace props which is not passed in DOM

NoWrap is css property so replace name to isNoWrap

 

2. (Recommend) Use prefix (styled-components@5.1v 👆)

Transient props v5.1
If you want to prevent props meant to be consumed by styled components from being passed to the underlying React node or rendered to the DOM element, you can prefix the prop name with a dollar sign ($), turning it into a transient prop.

So update NoWrap to $NoWrap. Why?

  • Better Performance
    When inproper property is given in styled-components, web browser would interpret and try to process it. So if dollar sign is given, it can be prevented.
  • Readability and Maintainence
    You can separate the property that's goint to pass in DOM or not.
  • Prevent code collision
    If property is used in styled components and browser has a collision, it might occur unexpected errors.

 

https://velog.io/@jiwonyyy/Styled-components%EC%97%90%EC%84%9C-props-%EB%98%91%EB%98%91%ED%95%98%EA%B2%8C-%EB%84%98%EA%B2%A8%EC%A3%BC%EA%B8%B0-feat.-Received-true-for-a-non-boolean-attribute

 

💅Styled-components에서 props 똑똑하게 넘겨주기 (feat. Received `true` for a non-boolean attribute)

styled-component에서 prefix를 사용하여 props를 전달해주자!

velog.io