[React] Styled-Component

iinnuyh_s·2023년 9월 11일
0

React

목록 보기
1/1

Styled Component


1. Styled Component 기본 문법

styled. + html태그

const Circle = styled.div`
	//css 정의
`;

2. props 사용

  1. prop에 따라 바뀔 CSS 속성이 하나일 경우
    • color = "blue" 라는 props 전달.
const Circle = styled.div`
	background = ${props=>props.color || 'black'};
`;

function App(){
	return <Circle color="blue"/>;
}
  1. prop에 따라 바뀔 CSS 속성이 여러개일 경우
    css 함수를 사용해서 여러개의 CSS 속성을 묶어서 정의.
const Circle = styled.div`
	background = 
	${ (props) =>
		props.primary && 
      	css`
			color : white;
			background : navy;
		`
	}
`;

3. component extend

  • 컴포넌트 요소 유지하면서 새로운 코드 추가함
  • 괄호를 사용하여 extends : styled(컴포넌트이름)
	const Button = styled.button`
	color : red;
	font-size:1em;
	`
    
    //Button 컴포넌트를 갖다 쓸 새로운 component
    const TomatoButton = styled(Button)`
	color : tomato,
	border-color : tomato;
	`

4. as

  • style 요소 유지하면서 html 태그만 바꾸고 싶을 때
	const Box = styled.div`
    background-color : red;
    `;
    
    function App(){
    	return(
        <Box as="span"></Box>
        );
    }

5. attrs

  • html attribute가 반복되는 component 만들 때
const Input = styled.input.attrs({required:true})`
background-color : blue;
`;

6. animation

  • keyframes helper 사용
    import {keyframes} from "styled-components";
    const rotateAnimation = keyframes`
    //animation 정의 - from {} to {} 설정
    `;
    
    const StyledBox = styled.div`
    	animation : ${rotateAnimation} 1s linear infinite;
    `;

7. Pseudo Selector (State selector)

  • Component 안에 있는 "다른 요소" target 할 때

  • &를 통해 자신이 포함된 상위 선택자를 지정할 수 있다.

       const Box = styled.div`
       background-color : black;
    
    		${Emoji} {
    			&:active {
    			transform: translateX(60px);
    			}
    		}
       `;
    	
    		function App(){
       	return(
             <Box>
             	<Emoji>👴</Emoji>
             </Box>
           );
       }
    

8. Themes

  • Dark mode / light mode
  • Dark mode -> Themes + Local Estate Management

0개의 댓글