React useRef

Dev_Sumni·2022년 5월 28일
post-thumbnail

바닐라 JS에서 form을 다루는 법

  • input element 가 필요하면 해당 dom 을 가져와서 사용

useRef

  • reference(특정 컴포넌트에 접근할 수 있는 객체)를 사용하기 위한 hook
  • ref를 넘겨주면, 해당 dom element 를 current(현재 참조하고 있는 element)에 담아줌 (= 변경 가능한 current를 가진 하나의 상자)
  • input(ref 변수)과 state의 차이점
    state는 값이 변경되었을때 함수 컴포넌트를 리렌더링 함
    ref 변수인 input에 뭔가를 대입한다거나 값을 변경한다거나 수정을 하여도 컴포넌트가 리렌더링 되지 않음 (영향 x)
  • ref는 값이 바뀌어도 컴포넌트가 re-render 되지 않음
  • react에 의한 re-render가 아닌,
    실제 document에 존재하는 element를 직접 접근하여 수정해야 함
  • react state로는 관리할 수 없는 경우에만 사용
  • 내부의 데이터가 변경되었을때 별도 알림 x
const refContainer = useRef(초기값);

🚩 useRef를 사용하여, Click to Reset 버튼을 클릭하면input의 value를 초기화하도록 만들어보기

const App = () => {
  const input = React.useRef(null);
  const handleClick = () => {
    if (input.current) {
    }
  }
  return (
    <div>
      <input type="text" ref={input} />
      <button type="button" onClick={handleClick}>Click to Reset</button>
    </div>
  );
}

const App = () => {
  const input = React.useRef(null);
  const handleClick = () => {
    if (input.current) {
      input.current.value = '';
    }
  }

🚩 현재 value는 ~~~ 입니다. 문구 추가해보기 (uncontrolled input)

const App = () => {
  const input = React.useRef(null);
  const handleClick = () => {
    if (input.current) {
      input.current.value = '';
    }
  }
 return (
    <div>
      <input type="text" ref={input} />
      <button type="button" onClick={handleClick}>Click to Reset</button>
    </div>
  );
}

const App = () => {
  const input = React.useRef(null);
  const [value, setValue] = React.useState('')
  const handleClick = () => {
    setValue('');
    if (input.current) {
      input.current.value = '';
    }
  }
 return (
    <div>
      현재 value는 {value}입니다.
      <input type="text" ref={input} onChange={(e) => setValue(e.target.value)} />
      <button type="button" onClick={handleClick}>Click to Reset</button>
    </div>
  );
}
  • setValue('') 가 누락된 경우
    // setValue('');

onCange 이벤트가 발생하지 않고, value가 업데이트 되지 않기 때문에 렌더가 일어나지 않음
= 버튼을 눌렀을때 이전 text 값이 남아있음

  • input.current.value reset이 누락된 경우
  //   if (input.current) {
  //     input.current.value = '';
  //   }

ref 실제 dom element에 접근해서 value를 초기화하는 문장을 사용하지 않기 때문에
= input에 이전 text 값이 남아있음

controlled input

const App = () => {
  const [value, setValue] = React.useState('');
  const handleClick = () => {
    setValue('');
  }
  return (
    <div>
      현재 value는 {value}입니다.
      <input type="text" **value={value}** onChange={(e) => setValue(e.target.value)} />
      <button type="button" onClick={handleClick}>Click to Reset</button>
    </div>
  );
}

🚩 reset 버튼을 누르면 input에 focus가 되도록 해보기

const App = () => {
  const [value, setValue] = React.useState('');
  const handleClick = () => {
    setValue('');
  }
  return (
    <div>
      <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />
      <button type="button" onClick={handleClick}>Click to Reset and Foucs!</button>
    </div>
  );
}

const App = () => {
  const input = React.useRef(null);
    const [value, setValue] = React.useState('');
    const handleClick = () => {
    setValue('');
    if (input.current) {
      input.current.focus();
    }
  }
  return (
    <div>
      <input type="text" ref={input} value={value} onChange={(e) => setValue(e.target.value)} />
      <button type="button" onClick={handleClick}>Click to Reset</button>
    </div>
  );
}
  • controlled input과 uncontrolled input은 상호배타적이지만, 필요하다면 ref는 어디서든 사용할 수 있음
profile
개발 일지 끄적 끄적,,

0개의 댓글