본 게시글은 구름EDU 처음 만난 React 온라인강의를 시청한 후 학습한 정보를 기록하는 목적의 게시글입니다.

생각의 흐름에 따라 작성된 게시글입니다. 가독성이 떨어질 수 있습니다.

처음 만난 React

 

처음 만난 React(리액트) - 구름EDU

굉장히 기초적인 내용 위주로 빠르고 쉽게 만나는 React! 웹 서비스를 위해 알아두어야 할 리액트 필수 개념을 짚어봅시다.

edu.goorm.io

구름 EDU

 

구름EDU - 모두를 위한 맞춤형 IT교육

구름EDU는 모두를 위한 맞춤형 IT교육 플랫폼입니다. 개인/학교/기업 및 기관 별 최적화된 IT교육 솔루션을 경험해보세요. 기초부터 실무 프로그래밍 교육, 전국 초중고/대학교 온라인 강의, 기업/

edu.goorm.io


Conditional Rendering

> Condition : 조건

> Conditional Rendering : 조건에 따른 렌더링

Component

function UserGreeting(props){

    return <h1>Welcome back!</h1>;

}

 

function GusetGreetong(props){

    return <h1>Please sign up.</h1>;

}

Conditional Rendering

function Greeting(props){

    const isLoggedIn = props.isLoggedIn;

    if(isLoggedIn){

        return <UserGreeting/>;

    }

    return <GusetGreetong/>;

}

 

ReactDOM.render(

    <Greeting isLoggedIn={false}/>,

    document.getElementById('root')

);

Element Variables

Component

function LogginButton(props){

    return(

        <button onClick={props.onClick}>

            Login

        </button>

    );

}

 

function LogOutButton(props){

    return(

        <button onClick={props.onClick}>

            Loout

        </button>

    );

}

Conditional Rendering

handleLoginClick(){

    this.setState({isLoggedIn: true});

}

 

handleLogoutClick(){

    this.setState({isLoggedIn: false});

}

 

render(){

    const isLoggedIn = this.state.isLoggedIn;

    let button;

 

    if(isLoggedIn){

        button = <LogOutButton onClick={this.handleLogoutClick} />;

    } else {

        button = <LogginButton onClick={this.handleLoginClick} />;

    }

 

    return(

        <div>

            <Greeting isLoggedIn={isLoggedIn}/>

            {button}

        </div>

    );

}

 

Inline Conditions

> 조건을 코드 안에 집어넣는 것

> if문의 경우 '&&' 연산자를 사용

true && expression -> expression

false && expression -> false

> if-Else문의 경우 '?' 연산자를 사용

condition ? true : false

Component Rendering을 막는 방법

null을 리턴하면 렌더링되지 않음


{Project Name} / src / Chapter07 / Greeting.js

import React from 'react';

 

function UserGreeting(props){

    return <h1>Welcome back!</h1>;

}

 

function GusetGreetong(props){

    return <h1>Please sign up.</h1>;

}

 

function Greeting(props){

    const isLoggedIn = props.isLoggedIn;

    if(isLoggedIn){

        return <UserGreeting/>;

    }

    return <GusetGreetong/>;

}

 

export default Greeting;

{Project Name} / src / index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

import Greeting from './Chapter07/Greeting';

 

ReactDOM.render(

  //Guest Rendering

  //<Greeting/>,

 

  //User Rendering

  <Greeting isLoggedIn={true}/>,

 

  document.getElementById('root')

);

reportWebVitals();

{Project Name} / src / Chapter07 / LoginControl.js

import React from 'react';

import Greeting from './Greeting';

 

function LogginButton(props){

    return(

        <button onClick={props.onClick}>

            Login

        </button>

    );

}

 

function LogOutButton(props){

    return(

        <button onClick={props.onClick}>

            Loout

        </button>

    );

}

 

class LoginControl extends React.Component{

    constructor(props){

        super(props);

        this.handleLoginClick = this.handleLoginClick.bind(this);

        this.this.handleLogoutClick = this.handleLogoutClick.bind(this);

        this.state = {isLoggedIn : false};

    }

 

    handleLoginClick(){

        this.setState({isLoggedIn: true});

    }

 

    handleLogoutClick(){

        this.setState({isLoggedIn: false});

    }

 

    render(){

        const isLoggedIn = this.state.isLoggedIn;

        let button;

   

        if(isLoggedIn){

            button = <LogOutButton onClick={this.handleLogoutClick} />;

        } else {

            button = <LogginButton onClick={this.handleLoginClick} />;

        }

   

        return(

            <div>

                <Greeting isLoggedIn={isLoggedIn}/>

                {button}

            </div>

        );

    }

}

 

export default LoginControl;

{Project Name} / src / index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

import LoginControl from './Chapter07/LoginControl';

 

ReactDOM.render(

  <LoginControl/>,

  document.getElementById('root')

);

reportWebVitals();

&& 연산자 사용해보기

{Project Name} / src / Chapter07 / LoginControl.js

...

        return(

            <div>

                <Greeting isLoggedIn={isLoggedIn}/>

                {button}

 

                {isLoggedIn &&

                    <h5>{new Date().toLocaleString()}</h5>}

            </div>

        );

...

CASE#1

...

        return(

            <div>

                <Greeting isLoggedIn={isLoggedIn}/>

                {button}

 

                {isLoggedIn &&

                    <h5>{new Date().toLocaleString()}</h5>}

                    <h5>{'How are you today?}</h5>

            </div>

        );

...

> Failed to compile : 인접한 JSX element는 하나의 태그로 둘러싸여야 한다!

CASE#2

...

        return(

            <div>

                <Greeting isLoggedIn={isLoggedIn}/>

                {button}

 

                {isLoggedIn &&

                    <div>

                        <h5>{new Date().toLocaleString()}</h5>

                        <h5>{'How are you today?'}</h5>

                    </div>}

            </div>

        );

...

> 하나의 div 태그로 묶어서 사용하자!

&&의 중첩

{Project Name} / src / Chapter07 / LoginControl.js

...

        let notiCount = 0;

        //let notiCount = 10;

 

        return(

            <div>

                <Greeting isLoggedIn={isLoggedIn}/>

                {button}

 

                {isLoggedIn &&

                    <div>

                        <h5>{new Date().toLocaleString()}</h5>

                        {notiCount > 0 &&

                            <h5>{'New noti: ' + notiCount}</h5>}

                    </div>}

            </div>

        );

...

? 연산자 사용해보기

...

        let notiCount = 0;

        //let notiCount = 10;

 

        return(

            <div>

                <Greeting isLoggedIn={isLoggedIn}/>

                {button}

 

                {isLoggedIn &&

                    <div>

                        <h5>{new Date().toLocaleString()}</h5>

                        {notiCount > 0 ?

                            <h5>{'New noti: ' + notiCount}</h5>

                            : <h5>{'No notification'}</h5>}

                    </div>}

            </div>

        );

...

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기