Development/React.js

조건부 렌더링

moretz0921 2022. 3. 15. 16:45

조건부 렌더링

1. 논리 연산자 활용
1) AND 연산자
: show 값이 true이면 렌더링하고, false이면 렌더링하지 않는다.

 

function App() {
  const [show, setShow] = useState(false);

  const handleClick = () => setShow(!show);

  return (
    <div>
      <button onClick={handleClick}>토글</button>
      {show && <p>보인다</p>}
    </div>
  );
}

export default App;

 


2) OR 연산자
: hide 값이 true이면 렌더링 하지 않고 false이면 렌더링 한다.  

 

import { useState } from 'react';

function App() {
  const [hide, setHide] = useState(true);

  const handleClick = () => setHide(!hide);

  return (
    <div>
      <button onClick={handleClick}>토글</button>
      {hide || <p>보인다</p>}
    </div>
  );
}

 


2. 삼항 연산자 활용하기 
: 삼항 연산자를 사용하면 참, 거짓일 경우에 다르게 렌더링해 줄 수 있다.

 

function App() {
  const [toggle, setToggle] = useState(false);

  const handleClick = () => setToggle(!toggle);

  return (
    <div>
      <button onClick={handleClick}>토글</button>
      {toggle ? <p>✅</p> : <p>❎</p>}
    </div>
  );
}

export default App;