React Framework

1. Next.js

- SSR( Server Side Rendering ) 방식으로, CRA의 경우 index.js만 불러와 SPA 방식으로 라우팅에 따라서 Component를 교체하는데, Next.js는 pages directory에 있는 파일을 기준으로 router별로 다른 page로 넘어가게 된다. 

- 요청한 page의 코드만을 로딩한다. -> 특정 page에서 에러가 발생하지 않더라도, 다른 page들은 잘 작동할 것.

- Browser의 View port에서 'Link' Component가 있을 때, 백그라운드에서 링크된 페이지를 위해 자동으로 프리패치(Prefetch)한다. [ Prefetch : 

 

2. Gatsby

- SSG( Static Site Generation ) 방식 Rendering

 

3. Create React App ( CRA )

- 가장 배우기 쉬움. 

- Client 측에서 rendering 하는데 필요한 HTML CODE를 생성한다. 

- SPA(Single Page Application)로, CSR( Client side rendering )방식이기 때문에 규모가 커지게 되어 js 파일의 용량이 커지게 되면 초기 로딩시간이 늘어나게 된다. -> CSR의 단점인 SEO 관련 문제도 발생 

- 무거운 작업들은 브라우저에서 수행된다. 

 

 

https://ko.reactjs.org/docs/create-a-new-react-app.html

https://geonlee.tistory.com/229

https://blog.outsider.ne.kr/1426

 

React 개발이 이렇게 쉬웠나? (Feat. Next.js)

해당 글은 제가 DEVIEW 2020의 발표 영상 DEVIEW 2020 - React 개발이 이렇게 쉬웠나? (Feat. Next.js)을 보면서 문서화 및 제 의견을 추가한 글입니다. 0.React 개발이 이렇게 쉬웠나? (Feat. Next.js) 1. UI Lib..

geonlee.tistory.com

 

728x90

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

[ React : Next.js ] _app.js  (0) 2021.11.23
[ React ] Next.js : React Framework + <Link>, CSN  (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

Hook

React v16.8에 추가된 기능으로, Class Component를 작성하지 않고도 state와 다른 React

의 기능들을 사용할 수 있게 해주는 기능이다. React Hook 나오기 전에는 Component의 상태를 관리하기 위해서는 Class Component를 작성하여 관리해 주어야 했다. 

 

Class Component state 관리 - this.state

React Hook 나오기 이전에 Class component로 state 관리를 하였다.

class component는 function component에 비해 복잡하고 오류 발생이 쉬우며 유지 보수가 힘들다. 

import React, { Component } from "react";

class UserFormClass extends Component{
	state = { name : "", email : "" };
    handleClick = ( { target : { name, value } } ) => {
    	this.setState({ [name] : value } );
    };
    
    render() {
    	const { name, email } = this.state;
        
        return(
        	<>
            	<label>
                	Name :
                    	<input type = "text" name ="name" value = {name} onChange={this.handleClick}/>
                </label>
                
                <label>
                	Email :
                    	<input type = "email" name = "email" value = {email} onChange = {this.handleClick}/>
                </label>
            </>
        );
    }
}

 

Function Component State 관리 - setState()

React Hooks에서 제공하는 useState() 함수를 사용하면 현재의 state 값과 이 값을 update하는 함수를 쌍으로 반환한다. state 값을 update해주는 함수를 event handler나 다른 곳에서 호출하여 state 값을 관리할 수 있다. 

 

// const [ < 상태 값 저장 변수 > , < 상태 값 갱신 함수 > ] = useState( < 상태 초기 값 > );
const [ UserName , setUerName ] = useState("");

※ 상태 값 갱신 함수를 사용하여 state를 변경하지 않고 state를 직접 다른 값으로 할당하거나 변경하면 해당 화면에 반영되지 않는다. state 값을 변경하려면 반드시 상태 값 갱신 함수를 사용하여 변경해주어야 한다. 

import React, { useState } from "react";

function UserFormFunction(){
	const [ name, setName ]= useState("");
    const [ email, setEmail ] = useState("");
    
    return (
    	<>
        	<label>
            	Name : 
                	<input
                    	type = "text"
                        name = "name"
                        value = {name}
                        onChange = { ( {target : {value} }) => setName(value)}/>
            </label>
            
            <label>
            	Email :
                	<input 
                    	type = "email"
                        name = "email"
                        value = {email}
                        onChange = { ( {target : { value } ) => setEmail(value)}/>
            </label>
        </>
    );
}

 


What Hook?

Hook은 function component에서 React State와 생명주기 기능 ( Lifecycle features ) 을 "연동(hook into)"할 수 있게 해주는 함수이다. 

- Hook은 class 안에서는 작동하지 않는다. 

- Hook은 class 없이 React를 사용할 수 있게 해준다.

 

1. 장점

- logic의 재사용 유연

- class component의 복잡성, 재사용성의 단점 해결

 

2. Hook API

- usetState

- useEffect

- useContext

- useRef

- useMemo

- useCallback..... 등등

 

 

 

 

출처 : https://ko.reactjs.org/docs/hooks-overview.html

728x90

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

[ React ] Next.js : React Framework + <Link>, CSN  (0) 2021.11.23
[ React ] React Framework  (0) 2021.11.23
[ React ] Styled-Components [1]  (0) 2021.11.16
[ React ] Component & Props  (4) 2021.11.16
[ React ] Element Rendering  (0) 2021.11.15

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

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

+ Recent posts