본문 바로가기
Front-End/React

[React] 7. 조건부 렌더링

by hongdor 2021. 2. 1.
728x90

출처: React 공식 홈페이지

조건부 렌더링 – React (reactjs.org)

 

 

1. if문을 통한 분기

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

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

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

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

 

 

2. State가 있는 버튼을 누르면 문구가 변하는 화면. State + if 활용. 대충보고 스킵하세용~

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

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

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

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

function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

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

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

 

 

3. 논리 연산자 사용

true && expression 은 항상 expression 이다.
false && expression 은 항상 false 이다.
앞의 조건이 true이면 expression이 출력되고
앞의 조건이 false라면 expression은 무시된다.

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

 

 

4. 유의할점

**공식문서 인용

- false로 평가될 수 있는 표현식을 반환하면 && 뒤에 있는 표현식은 건너뛰지만 false로 평가될 수 있는 표현식이 반환된다는 것에 주의필요

render() {
  const count = 0;
  return (
    <div>
      { count && <h1>Messages: {count}</h1>}
    </div>
  );
}

> 위 예시에서 count가 0이지만 {count}는 반환이 된다.
> <div>0</div> 반환.

 

 

5. 삼항연산자 사용 - (조건) ? (true일때 반환값) : (false일때 반환값)

 

예시1)

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

 

예시2)

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

 

 

6. null 반환

> 컴포넌트 자체를 숨긴다.

   null 반환을 메서드 생명주기 영향을 주지 않아서 state 값이 변하면 렌더링을 다시하는 것은 그대로 유지된다.

 

예시)

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

 

728x90

'Front-End > React' 카테고리의 다른 글

[React] 9. 폼  (0) 2021.02.03
[React] 8. 리스트와 Key  (0) 2021.02.03
[React] 6. 이벤트 처리하기  (0) 2021.02.01
[React] 5. State와 생명주기  (0) 2021.02.01
[React] 4. Component와 Props  (0) 2021.02.01

댓글