react 에서 document.querySelector() 를 사용하면 안되는 이유

김_리트리버·2020년 9월 29일
3

참고

전역 셀렉터는 코드를 쓴 컴포넌트에서만 검색하는것이 아니라 전체 document 에 대해서 검색한다.

즉 내가 원하는 특정 dom 뿐만 아니라 다른 컴포넌트에 있는 dom 에 접근할 수 있다.

ex> map을 사용하여 같은 컴포넌트인스턴스를 여러개 생성했다고 치자

// react jsx 

function getValue(e) {
let value = document.querySelector('.input')

console.log('value',value)
}

return(
<input className='input'onClick={getValue} />
<input className='input'onClick={getValue} />
<input className='input'onClick={getValue} />
<input className='input'onClick={getValue} />
<input className='input'onClick={getValue} />
)

document.querySelector 를 통해 특정 input 에서 값을 가져올 수 없게 된다.

때문에 react 에서는 hooks 기준으로 useRef() 를 사용하여 ref 를 element 에 부착하여

dom 에 접근하는 것이 권장된다.

profile
web-developer

0개의 댓글