IT/리액트

리액트 주요개념 - 조건부 렌더링

hanlabong 2022. 1. 16. 00:31
728x90

React에서는 원하는 동작을 캡슐화하는 컴포넌트를 만들고 애플리케이션의 상태에 따라 컴포넌트 중 몇 개만을 렌더링할 수 있습니다. 이때 if나 조건부 연산자와 같은 JavaScript 연산자를 사용합니다.

 

예를 들어 로그인 상태에 맞게 다른 문구를 보여줘야 한다면 다음과 같이 코드를 작성해야 합니다.

//ConditionalRendering.js

function UserGreeting(props) {
    return <h1>WelcomeBack!</h1>;
}

function GuestGreeting(props) {
    return <h1>Please sign up</h1>;
}

function Greeting(props) {
    const isLoggedIn = props.isLoggedIn;
    if(isLoggedIn) {
        return <UserGreeting />;
    }
    return <GuestGreeting />;
}

function ConditionalRendering() {
    return <Greeting isLoggedIn={false} />;
}

export default ConditionalRendering;

 

 

엘리먼트 변수

엘리먼트를 저장하기 위해 변수를 사용할 수 있는데 출력의 다른 부분은 변하지 않은 채로 컴포넌트의 일부를 조건부로 렌더링할 수 있습니다.

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 = {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.handleLoginClick} />;
        } else {
            button = <LoginButton onClick = {this.handleLogoutClick} />;
        }

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

function ConditionalRendering() {
    return <LoginControl />;
}

 

 

 

 

 

 

 

논리 && 연산자로 if를 인라인으로 표현하기

JSX 안에 중괄호를 이용해 표현식을 포함할 수 있는데 그 안에 논리 연산자 &&를 사용하면 쉽게 엘리먼트를 조건부로 넣을 수 있습니다.

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'];

function ConditionalRendering() {
    return (
        <div>
            <LoginControl />
            <Mailbox unreadMessages={messages} />
        </div>
    );
}

&& 앞의 조건이 true일 때 출력이 되고 false라면 무시하고 건너뜁니다.

 

 

조건부 연산자로 if-else 구문 인라인으로 표현하기

condition ? true : false 를 사용합니다.

render() {
  return (
    <div>
      <Greeting isLoggedIn={isLoggedIn} />
      {isLoggedIn
        ? <LogoutButton onClick = {this.handleLogoutClick} />
        : <LoginButton onClick = {this.handleLoginClick} />
      }
    </div>
  );
}

 

 

컴포넌트가 렌더링하는 것을 막기

다른 컴포넌트에 의해 렌더링될 때 컴포넌트 자체를 숨기고 싶을 때 렌더링 결과를 출력하는 대신 null을 반환하면 해결할 수 있습니다.

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.showWarning
        }));
    }

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

function ConditionalRendering() {
    return (
        <div>
            <Page />
        </div>
    );
}

컴포넌트의 render 메서드로부터 null을 반환하는 것은 생명주기 메서드 호출에 영향을 주지 않기 때문에 componentDidUpdate와 메서드가 계속해서 호출되게 할 수 있습니다.

728x90