ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [react] focus 에 대하여(동적,정적포커스,커서위치조정)
    react 2022. 1. 12. 16:34
    반응형

    input 창에 focus 주고 싶으면

     

    정적으로 주고싶을때는 input 태그에 autoFocus 속성을 넣어주면 된다

    <input type='text' autoFocus />

     

    근데 동적으로 줘야하는 경우도 있는데 그럴때 ref 를 이용한다.

    import { useRef } from 'react';
    
    const App = () => {
      const inputRef = useRef();
    
      useEffect(()=> inputRef.current.focus(),[??])
      
      return (
      	<input ref={inputRef} />
      )
    };

     

    근데 이렇게 동적으로 포커스를 줄때 이미 인풋창에 디폴트 값이 있는경우들이 있다.

    예를 들어 @로 시작하는 인풋창이여서 고정으로 있는경우라던가

     

    근데 동적으로 위와 같이 포커스를 잡아주게 되면 포커스는 제일 앞에 위치한다.

    ㅣ 표시를 커서로 봣을때

    내가 원하는 포커싱은 @ㅣ 이런 형태여야 하는데 ㅣ@ 이렇게 포커스가 잡힌다.

     

    그럴때 onFocus 이벤트 함수를 이용해서 커서 위치를 조정할수 있다.

    import { useRef } from 'react';
    
    const App = () => {
      const [value, setValue] = useState('@@@')
      const inputRef = useRef();
      
      const onFocus = (e: React.FocusEvent<HTMLInputElement>) => {
        const element = e.target;
        console.log(element.selectionStart); // log > 0
        console.log(element.value.length);  // log > 3
        element.selectionStart = element.value.length; // 커서 마지막으로 이동
      }
    
      useEffect(()=> inputRef.current.focus(),[??])
      
      return (
      	<input ref={inputRef} value={value} onFocus={onFocus} />
      )
    };

     

     

     

    'react' 카테고리의 다른 글

    [react] render 함수 와 가상돔에 대하여  (0) 2022.03.07
    [react] scroll handling  (0) 2022.02.11
    [react] forwardRef 사용해보기  (0) 2021.12.30
    next getinitialproperty()  (0) 2021.12.15
    Next.js css in js(styled component) (2)  (0) 2021.12.08
Designed by Tistory.