All files / src/chap07 HookCallbackRef.js

0% Statements 0/8
0% Branches 0/4
0% Functions 0/3
0% Lines 0/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                                                                                                                                           
import { useEffect, useRef, useState } from 'react';
 
export default function HookCallbackRef() {
  const [show, setShow] = useState(false);
  // 버튼 클릭으로 표시/숨기기 반전
  const handleClick = () => setShow(!show);
  // [주소]란 참조
  const address = useRef(null);
  // [주소] 항목이 비어있지 않으면 포커스 이동
  useEffect(() => {
    if (address.current) {
      address.current.focus();
    }
  }, [show]);
 
  return (
  <>
  <div>
      <label htmlFor="name">이름:</label>
      <input id="name" type="text" />
  </div>
  <div>
      <label htmlFor="email">이메일 주소:</label>
      <input id="email" type="text" />
      <button onClick={handleClick}>확장 표시</button>
  </div>
  {/* State(show) 값에 따라 [주소] 란을 표시 */}
  {show &&
    <div>
      <label htmlFor="address">주소:</label>
      <input id="address" type="text" ref={address} />
    </div>
  }
  </>
  );
}
 
 
 
// Code 7-2-12
// import { useEffect, useRef, useState } from 'react';
 
// export default function HookCallbackRef() {
//   const [show, setShow] = useState(false);
//   const handleClick = () => setShow(!show);
  
//   // 콜백 Ref 준비
//   const callbackRef = elem => elem?.focus();
 
//   return (
//   <>
//   <div>
//       <label htmlFor="name">이름:</label>
//       <input id="name" type="text" />
//   </div>
//   <div>
//       <label htmlFor="email">이메일 주소:</label>
//       <input id="email" type="text" />
//       <button onClick={handleClick}>확장 표시</button>
//   </div>
//   {/* State(show) 값에 따라 [주소] 란을 표시 */}
//   {show &&
//     <div>
//       <label htmlFor="address">주소:</label>
//       <input id="address" type="text" ref={callbackRef} />
//     </div>
//   }
//   </>
//   );
// }