[React] 리액트 Ref로 Dom 다루기 (useRef)

rondido·2022년 11월 10일
0

React

목록 보기
6/39
  • Input Element가 있고 화면이 뜨자마자 focus를 주고 싶다면 ?

?.focus()

  • Document

Document 인터페이스는 브라우저가 불러온 웹 페이지를 나타내며, 페이지 콘텐츠의 진입점 역할을 수행
DOM 트리는 <body><table> 및 여러 요소롤 포함.


<!DOCTYPE html>
<html lang="en">
    <style>
    .button {
        background-color: #4CAF50; /* Green */
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
      }
      
      .blue {background-color: #008CBA;} /* Blue */
      .red {background-color: #f44336;} /* Red */ 
      .black {background-color: #e7e7e7; color: black;} /* Gray */ 
      .gray {background-color: #555555;} /* Black */
      </style>
  <body>
    <script
      crossorigin
      src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"
    ></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    
    <div id="root"></div>

    <script type="text/babel">    
      const rootElement =document.getElementById("root");
      const App = () => {
        React.useEffect(()=>{
            
            document.getElementById("input").focus();
        },[])
        
        return(
            <>
                <input ref={inputRef}/>
            </>
        )        
    }
        
        ReactDOM.render(<App />,rootElement);
    </script>
  </body>
</html>

위 코드를 useRef를 통해 아래코드 처럼 바꿀 수 있다.

  const App = () => {
        const inputRef = React.useRef();
        React.useEffect(()=>{
            inputRef.current.focus();
            //document.getElementById("input").focus();
        },[])

현재는 focus를 통해 내가 선택하지 않아도 input이 선택된것을 확인 할 수 있다.
이거 유사하게 react hook에서 useRef를 사용하여 구현할 수 있다.
useRef는 특정한 값을 주지만 그것이 무조건 Element일 수 는 없다.
current라는 공간을 주고 거기 안에다가 Element를 준다.

또 한가지 예시 코드를 보도록 하자.

현재의 div 색깔은 갈색인데 1초 있다가 핑크색으로 변환 하겠다.

cript type="text/babel">    
      const rootElement =document.getElementById("root");
      const App = () => {
        const inputRef = React.useRef();
        const divRef = React.useRef();
        React.useEffect(()=>{
            inputRef.current.focus();
        setTimeout(() => {
            divRef.current.style.backgroundColor ='pink';
        }, 1000);
        },[])        
        return(
            <>
                <input ref={inputRef}/>
                <div 
                ref={divRef}
                style={{height:100, width:300 , backgroundColor:'brown'}} />
            </>
        )        
    }
        

document.getElementById를 사용하지 않고 왜 useRef라는 별도의 방법을 제공할까?

  • React는 스스로 Element들을 최적화해서 스스로 그리는 로직을 그린다.
    Dom APi를 이용하여 직접 Element에 도달하면 비효율이 나올 수도 있다.
    리액트에서 가지고 있는 스스로 고낮ㅇ하고 있는 틀 안에서 관장하기 위해서 제공

profile
개발 옆차기

0개의 댓글