Styled-Components

Installation 

npm install --save styled-components

or

yarn add styled-components

 

Example

styled-components는 template literal ( `` )을 사용하여, 요소의 style을 지정한다.

 

ex)

const Title = styled.h1`
	font-size : 1.5em;
    text-align : center;
    color : blue;
`;

const Wrapper = styled.section`
	padding : 4em;
    background : black;
`;

render(
	<Wrapper>
    	<Title>
        	Hello, World!
        </Title>
    </Wrapper>
);

/* 글씨 색상 blue, 배경 색 black인 Hello, World!가 출력 */

 

Use Props

const Btn = styled.button`
	color : ${ props => props.primary ? "pink" : "blue"};
    background : ${ props => props.primary ? "blue" : "pink"};
    
    font-size : 10px;
    margin : 10px;
`

render(
	<div>
    	<Btn>Normal</Btn>
        <Btn primay>Primary</Btn>
    </div>
);

/* props 값이 primary인 Button의 글씨 색 = pink , 배경색, blue */

 

Extending Styles ( 상속 )

styled() constructor를 통해서 다른 요소의 스타일을 상속할 수 있다.

const Button = styled.button`
	color : black;
    font-size : 1em;
 	margin : 1em;
    padding : 0.25em 1em;
    border : 2px solid black;
    border-radius : 3px;
`;

const TomatoButton = styled(Button)`
	color : tomato;
    border-color : tomato;
`;

render(
	<div>
    	<Button>Normal Button</Button>
        <TomatoButton>Tomato Button</TomatoButton>
    </div>
);

styled() structor를 통해서 TomatoButton은 Button component의 style을 상속받는다. TomatoButton은 color와 border-color 속성만 tomato로 바뀐 Button이다. 

 

Styling any component

 

const Link = ( { className, children } ) => (
	<a className = { className }>
    	{ children }
    </a>
);

const StyledLink = styled(Link)`
	color : pink;
    font-weight : bold;
`;

render (
	<div>
    	<Link>Unstyled, bording Link</Link>
        <br/>
        <StyledLink>Styled, exciting Link</StyledLink>
    </div>
);

 

passed component ( || )

|| 연산자를 사용하면 props 가 넘어오지 않은 경우, 기존 정의한 속성 유지.

const Input = styled.input`
	color : ${ props => props.inputColor || "blue" };
`

render(
	<div>
    	<Input defaultValue = "blue" type = "text"/>
        <Input defaultValue = "pink" type = "text" inputColor = "pink"/>
    </div>
);

/* 첫 번째  tag 는 색상 blue, 두 번째 tag는 색상 pink */

 

"as " polymorphic prop // 다형성

"as" 를 사용하여 다른 tag로도 사용가능. 

아래 예시를 보면, div tag에 button tag의 기능도 추가.

--> button 기능을하는 div tag

ex)  

const Component = styled.div`
	color : red;
`;

render(
	<Comment
    	as = "button"
        onClick = { () => alert("hello") }
        >
        Hello
        </Comment>
);

/* button tag 의 속성을 가진 Comment component*/

 

 

출처 : https://styled-components.com/docs/basics#motivation

728x90

'Framework\Library > React' 카테고리의 다른 글

[ React ] React Framework  (0) 2021.11.23
[ React ] Hook - state  (0) 2021.11.22
[ React ] Component & Props  (4) 2021.11.16
[ React ] Element Rendering  (0) 2021.11.15
[ React ] JSX  (0) 2021.11.15

+ Recent posts