[React]-조건부 렌더링

2020. 8. 18. 00:58개발/React

아래 글은 React Document 를 바탕으로 작성되었다.

조건부 렌더링

React에서는 원하는 동작을 캡슐화하는 컴포넌트를 만들 수 있다. 이렇게 하면 애플리케이션의 상태에 따라 컴포넌트 중 몇 개 만을 렌더링 할 수 있다.

React에서 조건부 렌더링은 javaScript에서의 조건 처리와 같이 동작한다. if나 조건부 연산자(삼항 연산자) 와 같은 JavaScript 연산자를 현재 상태를 나타내는 엘리먼트를 만드는데 사용해라. 그러면 React는 현재 상태에 맞게 UI를 업데이트 할 것이다.

  • 요약 : if삼항 연산자를 사용해 조건부 렌더링이 가능하다

이 컴포넌트는 현재 상태에 맞게 <LoginButton /> 이나 <LogoutButton /> 을 렌더링 한다.

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

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

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

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

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

JavaScript에서 true && expression은 항상 expression이고, false && expression은 항상 false 이다.

따라서 && 뒤의 엘리먼트는 조건이 true일 때만 출력된다. 조건이 false라면 React는 무시한다.


삼항 연산자로 표현하기

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

가독성은 떨어지지만 이렇게도 표현할 수 있다.


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

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

props.warnfalse이면 <WarningBanner /> 는 렌더링 되지 않는다.

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

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

'개발 > React' 카테고리의 다른 글

[React]-React로 사고하기  (0) 2020.08.18
[React]-리스트와 Key  (0) 2020.08.18
[React]-이벤트 처리하기  (0) 2020.08.18
[React]-Component와 Props  (0) 2020.08.18
[React] - 엘리먼트 렌더링  (0) 2020.08.17