Conditional Rendering

nothing-99·2022년 9월 23일
0

react

목록 보기
4/4
post-thumbnail

조건에 따라서 rendering 을 다르게 할 수 있다.

  • if ~ else
  • inline JSX
    - e1 && e2
    - condition ? e1 : e2
  • return null

if ~ else

  • item을 샀을 경우 Sell button
  • item을 팔았을 경우 Buy button
// BuyButton
function BuyButton(props) {
  return <button onClick={props.onClick}>Buy</button>;
}
// SellButton
function SellButton(props) {
  return <button onClick={props.onClick}>Sell</button>;
}
// ButtonControl
class ButtonControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isMine: false };
    this.handleBuyClick = this.handleBuyClick.bind(this);
    this.handleSellClick = this.handleSellClick.bind(this);
  }
  handleBuyClick() {
    this.setState({isMine: true});
  }
  handleSellClick() {
    this.setState({isMine: false});
  }
  render() {
    const isMine = this.state.isMine;
    let button;
    if (isMine) {
      button = <SellButton onClick={this.handleSellClick} />;
    } else {
      button = <BuyButton onClick={this.handleBuyClick} />;
    }
    return (
      <div>
        <span>Item</span>
        {button}
      </div>
    );
  }
}

condition ? e1 : e2

render() {
  const isMine = this.state.isMine;
  return (
    <div>
      {isMine 
        ? <SellButton onClick={this.handleSellClick} />
        : <BuyButton onClick={this.handleBuyClick} />}
    </div>
  )
}

e1 && e2

e1 && e2 는 AND 와 같은 표현이다. e1, e2가 모두 참이어야 e1 && e2는 참이 된다. 해당 표현식이 참인지 거짓인지 판단할 수 있을 때까지 검사한다 이것만 생각하면 크게 어렵지 않다.

e1 이 참일 경우, e1 && e2 가 참인지 거짓인지 판단하기 위해서 e2가 참인지 거짓인지 검사할 필요가 있기 때문에 e2까지 확인한다.

e1 이 거짓일 경우, e1 && e2 가 거짓이라는 것이 바로 나오기 때문에 e2를 검사하지 않고 이 구문에 대한 실행은 종료한다.

쉽다!! e1이 참이면 e2가 output 되고 e1이 거짓이면 e1이 output된다. ( 검사를 종료하는 지점에서 output된다 )

function MyNft(props) {
  const myNfts = props.nfts;
  return (
    <div>
        {myNfts.length > 0 && 
          <span>
            I have {myNfts.length} nfts.
          </span>}
    </div>
  )
} 

function App() {
  const nfts = ['rayc', 'yyc', 'vac'];
  return (
    <>
      <MyNft nfts={nfts}/>
    </>
  )
}
  • myNfts의 길이가 0인 경우 myNfts.length > 0은 거짓이기 때문에 여기서 종료된다. (즉, 뒤의 expression은 거들떠도 보지 않는다)
  • myNfts의 길이가 0 이상인 경우 myNfts.length > 0은 참이기 때문에 뒤의 expression이 참인지 거짓인지 보러 가기 때문에 뒤의 expression이 output 된다.

return null

render() 실행결과가 null인 경우 아무것도 표현되지 않는다. 하지만 lifecycle method 의 실행여부에는 어떠한 영향도 끼치지 않는다. 그대로 실행됨.

class ButtonControll extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isOn: false,
      test: false
    };
    this.handleToggleClick = this.handleToggleClick.bind(this);
    this.handleTestClick = this.handleTestClick.bind(this);
  }
  handleToggleClick() {
    this.setState(state => ({isOn: !state.isOn}));
  }
  handleTestClick() {
    this.setState(state => ({test: !state.test}));
  }
  componentDidUpdate() {
    console.log('Updated!');
  }
  render() {
    if (this.state.test) return null;
    return (
      <div>
        <button onClick={this.handleToggleClick}>
          {this.state.isOn ? 'ON' : 'OFF'}
        </button>
        <button onClick={this.handleTestClick}>
          BYE
        </button>
      </div>
    )
  }
}
  • BYE 를 클릭하면 아무것도 rendering 되지 않지만 componentDidUpdate()를 실행해서 console 창에 'Updated!' 가 출력된다.

출처

profile
- RAYC, Vaping Ape, Bitcoin Monkeys holder

0개의 댓글