'css'는 'styled-components' 라이브러리에서 제공하는 함수로, CSS를 작성할 수 있는 방식 중 하나이다.
'css' 함수를 사용하면 CSS코드를 작성하고, 이를 자바스크립트 변수로 저장하고 재사용 가능하다.
아래코드에서 'const buttonStyles = css'는 'styled-components'의 css 함수를 사용하여 CSS 속성을 정의한 것이다. 이렇게 정의된 CSS 속성은 다른 'styled-components' 스타일 컴포넌트에서도 재사용할 수 있다. 이는 코드의 재사용성을 높여서 작성해야할 CSS 코드의 양을 줄이고, 유지보수성을 높일 수 있다.
1. ButtonStyles.js
import { css } from "styled-components";
const buttonStyles = css`
cursor: pointer;
border-radius: 8px;
height: 50px;
width: 200px;
font-weight: 600;
background-color: rgb(255, 255, 255);
`;
export default buttonStyles;
${props => ...}는 styled-components에서 props를 받아서 해당 CSS 속성을 동적으로 변경할 수 있는 기능이다. 이를 "styled-components의 props" 또는 "interpolated function" 이라고도 한다.
여기서 props는 해당 컴포넌트가 렌더링될 때 전달되는 속성값(property)들을 객체 형태로 가지고 있는 변수이다. 예를 들어, small 속성값이 해당 컴포넌트에 전달되면, props.small은 true가 된다.
따라서, 위 코드에서 ${props => props.small && css는 props 객체 안에 small 속성값이 전달되면 그 값이 true이면, css 함수를 실행하라는 의미이다. && 연산자("and")는 좌항이 true일 때만 우항을 실행하기 때문에, props.small이 true일 때만 해당 CSS 속성을 적용하게 된다!
정리하면 'props.small && css'는 'props' 객체의 small 속성이 truthy한 경우에만 css를 반환하도록 하는 것이다.
위랑 같은말
props.small은 Button 컴포넌트에서 small prop이 전달되었는지 여부를 나타내며, css 함수는 해당 CSS 속성을 동적으로 생성하기 위한 함수이다. 이 경우 props.small이 true인 경우에만 해당 CSS 속성이 생성되어 적용된다.
즉, 위 코드에서 ${props => props.small && css ... }는 small prop이 전달되면 해당 CSS 속성('small' 스타일)을 동적으로 생성하고, 그렇지 않으면 해당 CSS 속성을 생성하지 않는다(일반적인 스타일).
2. Button.jsx
import React from 'react'
import styled from 'styled-components'
import buttonStyles from '../styles/ButtonStyles'
import { css } from 'styled-components'
const Button = () => {
return (
<>
<PrimaryButton>Large Primary Button</PrimaryButton>
<PrimaryButton medium>Medium</PrimaryButton>
<PrimaryButton small>Small</PrimaryButton>
</>
)
}
export default Button;
const PrimaryButton = styled.button`
${buttonStyles}
border: 3px solid rgb(85, 239, 196);
color: rgb(0, 0, 0);
${props =>
props.medium && css`
border: none;
background-color: rgb(85, 239, 196);
height: 45px;
width: 130px;
`}
${props =>
props.small && css`
border: none;
background-color: rgb(85, 239, 196);
height: 40px;
width: 100px;
`}
`
'메모장' 카테고리의 다른 글
라이프사이클(클래스형 vs 함수형), React hooks (0) | 2023.04.30 |
---|---|
리액트 설치 명령어 (0) | 2023.04.29 |
UUID(범용 고유 식별자) (0) | 2023.04.24 |
State, Props, 리-렌더링 발생 조건 (0) | 2023.04.23 |
팬명록에 별점 넣기(응용) (0) | 2023.03.22 |