React 기초

[React] 조건부 렌더링 (6)

Evolving Developer 2023. 2. 8. 08:42

로그인 / 로그아웃 예제

- isLoggedIn이 true면 <UserGreeting />로 렌더링

- isLoggedIn이 false면 <GuestGreeting />로 렌더링

function UserGreeting(props) { // 로그인 후
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) { // 로그인 전
  return <h1>Please sign up.</h1>;
}

- Greeting() 메서드 -> isLoggedIn 값에 따른 조건부 렌더링

function Greeting(props) { // if문으로 어디로 렌더링 할지 결정
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Greeting isLoggedIn={false} />);

- 로그인/로그아웃에 따른 버튼의 변화

 

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}; // 처음 상태는 false
  }

  handleLoginClick() { // 로그인 시 동작하는 이벤트 핸들러
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() { // 로그아웃 시 동작하는 이벤트 핸들러
    this.setState({isLoggedIn: false});
  }
  
  function Greeting(props) { // if문으로 어디로 렌더링 할지 결정
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

  render() {
    const isLoggedIn = this.state.isLoggedIn; // 초기 상태는 false -> true -> false -> ...
    let button; // button이라는 변수 선언
    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />; // button에 컴포넌트 담기
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} /> // props.isLoggedIn으로 true/false 넘겨줌
        {button}
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<LoginControl />);

If 대신 논리연산자 && 사용하기

- true면 출력

- false면 생략

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 && // unreadMessages의 길이가 0보다 커야 아래 <h2></h2>가 출력됨
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      } // 만약 unreadMessages.length == 0이라면 <h2></h2> 출력 X
    </div>
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Mailbox unreadMessages={messages} />);

- JS에서 true && expression은 expression -> 표현식 보여줌

- JS에서 false && expression은 false -> 건너뜀

 

If-Else 대신 조건부 연산자 사용하기

- condition ? true : false

- true면 a 출력

- false면 b 출력

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}

- inLoggedIn이 true라면 'currently' 출력

- inLoggedIn이 false라면 'not' 출력

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

 

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

- 어떤 컴포넌트 A가 다른 컴포넌트 B에 의해 렌더링 될 때, 컴포넌트 A 자체를 숨기고 싶을 때 

- return null 을 활용하면 숨기기 가능

function WarningBanner(props) {
  if (!props.warn) { // 만약 props.warn이 false라면 (안전한 상태라면)
    return null; // 리턴 0 -> 아래 구문 실행 X
  }

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

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {showWarning: true}; // 시작은 warning이 보이는 상태
    this.handleToggleClick = this.handleToggleClick.bind(this); // 바인드
  }

  handleToggleClick() {
    this.setState(state => ({ // state의 이전 상태를 인자로 받고
      showWarning: !state.showWarning // state 상태 바꾸기
    }));
  }

  render() {
    return (
      <div>
        <WarningBanner warn={this.state.showWarning} />
        <button onClick={this.handleToggleClick}> // state의 상태를 바꿔줌
          {this.state.showWarning ? 'Hide' : 'Show'} // true/false에 따라 버튼의 내용이 달라짐
        </button>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Page />);