안녕하세요, 피터팬입니다!
오늘은 useRef로 input 상태를 관리해볼 건데요.
https://peter-coding.tistory.com/204?category=1287898
[React] useState로 input 상태 관리하기
이번에 해볼 것은 input요소에서 사용자가 입력한/선택한 값을 제어해볼 건데요! let으로 선언한 변수는 JS내에서 변경은 가능하지만, 값이 변경되었다고 다시 렌더링 하지 않습니다. useState로 선
peter-coding.tistory.com
지금까지는 위에서처럼 useState를 이용하여 input 상태를 관리해왔습니다.
useRef를 이용하면 더 간편하게 input상태를 관리할 수 있습니다.
적용법
import {useRef} from 'react'
사용법
inputRef.current에서 유용하게 쓰일 값으로는 value, focuse()가 있습니다.
const inputRef = useRef();
console.log(inputRef)
...
<input ref={inputRef}/>
예시
const inputRef = useRef();
const handleButton = () =>{
if(inputRef.current.value===""){
inputRef.current.focus();
}else{
inputRef.current.value="";
}
}
...
<input ref={inputRef}/>
<button conClick={handleButton}>Click!</button>
Reference
https://react.vlpt.us/basic/10-useRef.html
10. useRef 로 특정 DOM 선택하기 · GitBook
10. useRef 로 특정 DOM 선택하기 JavaScript 를 사용 할 때에는, 우리가 특정 DOM 을 선택해야 하는 상황에 getElementById, querySelector 같은 DOM Selector 함수를 사용해서 DOM 을 선택합니다. 리액트를 사용하는
react.vlpt.us
'WebProgramming > React' 카테고리의 다른 글
[React] Component에서 Componet로 배열 전달하기 (0) | 2022.07.26 |
---|---|
[React] useContext를 이용해 전역 props전달하기 2 (context.js로 분리시키기) (0) | 2022.07.22 |
[React] useEffect를 이용한 DOM조작 (0) | 2022.07.22 |
[React] useReducer를 이용한 상태관리 (0) | 2022.07.22 |
[React] Createportal을 이용해 특정 요소에 하위 요소 추가하기 (0) | 2022.07.21 |
[React] CSS Module을 이용한 컴포넌트 스타일링 (0) | 2022.07.20 |
[React] styled-component를 이용한 컴포넌트 스타일링 (0) | 2022.07.20 |
[React] Checkbox 값 제어하기 (0) | 2022.07.17 |