프로젝트가 90프로 완성이 되고 이걸 발견하였다.
dom에 접근해서 textContent부터 애니메이션을 신나게 주물럭 거렸다.
하지만 이렇게하면 안된다고 한다.
예시를 보자
import React from 'react'
const User = () => {
const requestToLogin = event => {
event.preventDefault()
const idReference = document.getElementById('id')
const passwordReferenece = document.getElementById('password')
const id = idReference.target.value
const password = passwordReferenece.target.value
// a AJAX logic
}
return (
<form onSubmit={requestToLogin}>
<label>
id:
<input id='id' type='text' />
</label>
<label>
password:
<input id='password' type='password' />
</label>
<button type='submit'>로그인!</button>
</form>
)
}
바로 2시간전의 내가 사용하는 dom 접근 방법이었다. 그런데 이렇게 id만들어 접근하게 되면 index로 dom을 모으는 과정에서 id가 중복되어 버리는 불상사가 일어난다.
거금 42000원을 주고 산 리액트를 다루는 기술에선 함수형 컴포넌트에서 날먹 할 수 있는 hook인 useRef를 소개해 주었다.
이제 완전히 달라진 코드를 봐보자
import React, { useRef } from 'react'
const User = () => {
const idReferenece = useRef()
const passwordReference = useRef()
// ...
return (
<form>
<label>
id:
<input ref={idReference} type='text' />
</label>
<label>
password:
<input ref={passwordReference} type='password' />
</label>
<button type='submit'>로그인!</button>
</form>
)
}
지렸다. 근데 이제 뭐함? 애니메이션 어케 만듬?? isReference.current하면 스타일이고 뭐고 쫙 뜨는 개 쩌는 prototype을 볼 수 있다.
출처:https://velog.io/@public_danuel/trendy-react-useref#useref 감사합니당