Home React 04. Conditional Rendering
Post
Cancel

React 04. Conditional Rendering

React에서 조건에 따라 Components를 다르게 렌더링할 수 있다. 조건부 렌더링을 하는 방법은 세 가지가 있다.

  1. 요소 변수
  2. 논리 연산자 ‘&&’
  3. 삼항 연산자

요소 변수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    function LoginButton(props) {
        return (
            <button onClick={props.onClick}>
                Login
            </button>
        );
    }

    function LogoutButton(props) {
        return (
            <button onClick={props.onClick}>
                Logout
            </button>
        )
    }

    class LoginControl extends React.Component {
        constructor(props) {
            super(props);
            this.handleLoginClick = this.handleLoginClick.bind(this);
            this.handleLogoutClick = this.handleLogoutClick.bind(this);
            this.state = {isLoggeIn: 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 = <LoginButton onClick={this.handleLoginClick} />;
            }

            return (
                <div>
                    <Greeting> isLoggedIn={isLoggedIn} />
                    {button}
                </div>
            );
        }
    }

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

isLoggedIn 의 상태에 의존하여 렌더링하는 Component가 달라진다.

‘&&’ 논리 연산자

Javascript && 논리 연산자를 이용하면 Inline 방식으로 조건부 렌더링이 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    function Mailbox(props) {
        const unreadMessages = props.unreadMessages;
        return (
            <div>
                <h1>Hello!</h1>
                {unreadMessages.length > 0 &&
                    <h2>
                        You have {unreadMessages.length} unread messages.
                    </h2>
                }
            </div>
        );
    }

    const messages = ['React', 'Re: React', 'Re:Re: React'];
    ReactDOM.render(
        <Mailbox unreadMessages={messages} />,
        document.getElementById('root')
    );

&& 논리 연산자는 treu && 값일 경우 항상 값으로 계산이 되고, false && 값일 경우 항상 false로 계산된다. 또한 0 && 값일 경우 항상 0으로 계산된다.

삼항 연산자

삼항 연산자는 ** 조건 ? true : false ** 의 구조로 이루어 진다.

1
2
3
4
5
6
7
8
    render() {
        const isLoggedIn = this.state.isLoggedIn;
        return (
            <div>
                The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
            </div>
        );
    }

isLoggedIn이 true일 경우 ‘currently’를, false일 경우 ‘not’을 출력한다.

렌더링 방지

렌더링된 component를 특정 경우에 따라 숨기고 싶을 때, null을 반환해서 숨길 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    function WarningBanner(props) {
        if (!props.warn) {
            return null;
        }

        return (
            <div className="warning">
                Warning;
            </div>
        );
    }

    class Page extends React.Component {
        constructor(props) {
            super(props);
            this.state = {showWarning: true};
            this.handleToggleClick = this.handleToggleClick.bind(this);
        }

        handleToggleClick() {
            this.setState(state => ({
                showWarning: !state.showWaring
            }));
        }

        render() {
            return (
                <div>
                    <WarningBanner warn={this.state.showWarning} />
                    <button onClick={this.handleToggleClick}>
                        {this.state.showWarning ? 'Hide' : 'Show'}
                    </button>
                </div>
            );
        }
    }

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

WarningBanner component는 warn prop 값에 따라 렌더링 된다. warn이 false일 경우 null값을 반환하며, 렌더링 되지 않는다.

This post is licensed under CC BY 4.0 by the author.