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

& Ampersand

상위 선택자 참조.

 

ex 1)

.btn {
	position : absolute;
}

.btn.active {
	color : blue;
}


/* Ampersand 활용 */

.btn{
	position : absolute;
    
    // & 가 btn으로 치환된다. 
    &.active{
    	color : blue;
    }
}

 

ex 2)

.list li : last-child {
	margin : 20px;
}

/* Ampersand 적용 */
.list {
	li{
    	// &가 li로 치환된다. 
    	&:last-child{
    		margin : 20px;
        }
    }
}

 

출처 :

https://sso-feeling.tistory.com/232

https://velog.io/@jch9537/CSS-SCSS-SASS

 

[SCSS]Ampersand &(상위 선택자 참조)

CSS에서는 .btn클래스와 .active클래스를 같이 가지고 있는 것이 있다. SCSS에서는 &기호를 사용하여 표현한다. &가 상위 태그로 치환이 된다. 첫번째는 .btn으로 치환되고 두번쨰는 li로 치환이 되는

sso-feeling.tistory.com

 

728x90

'WEB > CSS' 카테고리의 다른 글

[ Web : CSS ] positon  (0) 2022.07.27
[ Web : CSS ] flexbox  (0) 2021.11.29
[ Web - CSS media queries ] 반응형 웹  (0) 2021.11.17

Component

Component는 "Props"라는 임의의 입력을 받은 후, React Element를 반환한다. 

Component는 function Component와 Class Component 두 가지 유형으로 나뉜다. 

function Component를 정의하는 가장 간단한 방법은 Javascript 함수를 작성하는 것이다. 

class Component는 'extends React.Componet'와 render()가 포함되어야 한다. 

 

Function Component

function Welcome(props){
	return <h1>Hello, {props.name}</h1>;
}

 

Class Component

class Welcome extends React.Component{
	render(){
    	return <h1>Hello, {this.props.name}</h1>;
    }
}

 

Component Composition ( 합성 )

ex) 

function Welcome(props){
	return <h1>Hello, {props.name}</h1>;
}

function App(){
	return(
    	<div>
        	<Welcome name = "Sara"/>
            <Welcome name = "Cahal"/>
            <Welcome name = "Edite"/>
        </div>
    );
}

ReactDOM.render(
	<App />,
    document.getElementById('root')
);

 

Component Extraction

복잡하게 중첩된 구조의 Component에서 여러개의 Component로 쪼개는( 추출하는 ) 것.

 

ex) 

function Coment(props){
	return (
    	<div className = "Comment">
        	<div className = "UserInfo">
            	<img className = "Avatar" src = { props.author.avatarUrl } alt = { props.author.name }/>
            	<div className = "UserInfo-name"> { props.auhtor.name } </div>
            </div>
            <div className = "Comment-text"> { props.text } </div>
            <div className = "Comment-date"> { formatDate(props.date) } </div>
        </div>
    );
}

위 코드와 같이 중첩된 구조의 Component의 경우에는 나중에 구성요소들을 변경하기 어려울 수 있고, 각 구성요소들을 개별적으로 재사용하기 힘들다는 단점이 있어 Component를 쪼개어 사용하면 좋다. 

 

아래 코드는 위 Component에서 Avatar를 Extraction한 것이다. 

function Avatar(props){
	// Avatar Extraction
	retrun(
    		<img className = "Avatar"
            src = { props.user.avatarUrl }
            alt = { props.user.name }
            />
    );
}

 

// Avatar Component 적용

function Comment(props){
	return (
    	<div className = "Comment">
        	<div className = "UserInfo">
            	// 추출한 Avatar Component
            	<Avatar user = { props.author } />
            	<div className = "UserInfo-name">
            		{ props.author.name }
                </div>
            </div>
            <div className = "Comment-text">
            	{ props.text }
            </div>
            <div className = "Comment-date">
            	{ formatDate(props.date) }
            </div>
        </div>
    );
}

 

// UserInfo Component Extraction

function UserInfo(props){
	return( 
    	<div className = "UserInfo">
        	<Avatar user = { props.user } />
            <div className = "UserInfo-name-">
            	{ props.user.name }
            </div>
        </div>
    );
}

 

// UserInfo Component 적용

function Comment(props){
	retrun (
    	<div className = "Comment">
        	<UserInfo user = { props.author }/>
            <div className = "Comment-text">
            	{ props.text }
            </div>
            <div className = "Comment-date">
            	{ formatDate(props.date) }
            </div>
        </div>
    );
}

 

Props

- Props는 읽기 전용

- 모든 React Component는 자신의 props를 다룰 때 반드시 순수 함수 처럼 동작해야 한다.

 

순수함수 ? 

=> 순수함수는 어떤 인자를 받던 간에 동일한 인자의 경우 항상 같은 값을 리턴하는 함수를 의미.


[ + ] 

const props = { 
	a : 3 
    b : 4
};

///////////////////////////////////////////////////////////////////////////////////

// a 접근 시 
// props.a

 

[ + ]

// props = { a, b }
// 아래 두개 동일

function Component(props)
function Component( { a, b } )

 

출처 : https://ko.reactjs.org/docs/components-and-props.html

728x90

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

[ React ] React Framework  (0) 2021.11.23
[ React ] Hook - state  (0) 2021.11.22
[ React ] Styled-Components [1]  (0) 2021.11.16
[ React ] Element Rendering  (0) 2021.11.15
[ React ] JSX  (0) 2021.11.15

Element

React app의 가장 작은 단위로, screen에 표시할 content를 표현.

ex)

const element = <h1>Hello, world</h1>;

Browser DOM Element와 달리 React Element 는 일반 객체이며, 쉽게 생성이 가능하다. ReactDOM은 React element와 일치하도록 DOM을 Update해준다. 

 

※ Element는 Component의 구성요소.

※ React Element는 불변객체로서, Element를 생성한 이후에는 해당 element의 자식이나 속성을 변경할 수 없기 때문에 UI를 새로 Update하기 위해서는 새로운 Element를 생성하여 ReactDOM.render() 로 전달하여 redering해줘야 한다. 

 

[ + ] React Element는 사용자 정의 Component로도 나타낼 수 있다.

ex) 

function Welcome(props){
	return <h1>Hello, {props.name}</h1>;
}


const element = <Welcome name ="Sara"/>;
ReactDOM.render(
	element, 
    document.getElementById('root')
);

과정 : 

1) <Welcome name = "Sara"/> element로 ReactDOM.render() 호출

2) props 값 : { name : 'Sara' } 를 Welcome component로

3) Welcome Component의 결과로 <h1>Hello, Sara</h1> element 반환

4) ReactDOM은 반환된 해당 element( <h1>Hello, Sara</h1> ) 와 DOM이 일치하도록 UPDATE

 

결과 값 => Hello, Sara

 

 

728x90

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

[ React ] React Framework  (0) 2021.11.23
[ React ] Hook - state  (0) 2021.11.22
[ React ] Styled-Components [1]  (0) 2021.11.16
[ React ] Component & Props  (4) 2021.11.16
[ React ] JSX  (0) 2021.11.15

+ Recent posts