FrontEnd

useRef 개념정리

Taemin Kim 2022. 11. 16. 15:29

useRef는 dom을 변경할 때 사용한다

import "./App.css";
import {createRef,useEffect,useRef,useState} from "react";

//useRef(디자인)
//dom을 변경할 때 사용

function App() {

    const myRef=useRef(null);


    const [list,setList]=useState([{id:1,name:"길동"},{id:2,name:"꺽정"}]);
    const myRefs= Array.from({length:list.length}).map(()=>createRef());

    return(

    <div>
        <button onClick={()=>{
            console.log(myRef);
            console.log(myRef.current);
            // myRef.current.style.backgroundColor='red';

            myRefs[1].current.style.backgroundColor='red';
        }}>색 변경
        </button>

        <div ref={myRef}>박스</div>

        {list.map((user,index)=>(
            <h1 ref={myRefs[index]}>{user.name}</h1>
        ))}
    </div>

  );

}
export default App;

createRef라는 것을 사용해서 동적으로 레퍼런스를 생성해주는 함수가 있다

myRef가 배열로 만들어진다

[0], [1], [2] 이런식으로 출력할 수 있게 해준다