로그인 사용자와 게스트 사용자를 조건을 통해서 element를 렌더링이 가능

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

ReactDOM.render(
  // Try changing to isLoggedIn={true}:
  <Greeting isLoggedIn={false} />,
  document.getElementById('root')
);

login/logout 버튼 변경하기 상태에 따라 LogoutButton, LoginButton element를 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.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

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

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

이렇게 분기하는게 좋을까? 분기를 해야하는 깊이가 커지면 모든 경우에 따라 처리를 해줘야 하겠구나. 두가지 조건이 있는 경우에는 두 조건의 조건부 렌더링을 해주는 컴포넌트(함수)를 만드는게 좋겠다.

+ Recent posts