- React
hooks 라이브러리 - useRef
나둥식
2022. 11. 3. 17:58
🔎 useRef
: dom을 변경할 때 사용
- html(요소)나 컴포넌트의 메모리 주소를 가져와 객체(래퍼런스) 형식으로 관리할 수 있음
- current 속성을 가지고 있는 객체는 반환한다.
- current 값이 바뀌어도 재렌더링 되지 않음
- 재렌더링시에 current 값는 사라지지 않음
1️⃣ 색상 변경하기
① 박스 배경색 디자인
import { useRef } from 'react';
import './App.css';
// useRef(디자인)
// dom을 변경할 때 사용
function App() {
const myRef = useRef(null);
return (
<div>
<button onClick={()=>{myRef.current.style.backgroundColor='red';}}>색변경</button>
<div ref={myRef}>박스</div>
</div>
);
}
export default App;
색변경 버튼 클릭시 <div>박스</div>의 backgroundColor가 red로 변경됨
② 콘솔창에서 값 확인해보기
return (
<div>
<button onClick={()=>{
console.log(myRef);
console.log(myRef.current);
myRef.current.style.backgroundColor='red';}}>
색변경
</button>
<div ref={myRef}>박스</div>
</div>
);
current의 style값이 myRef에 들어옴
2️⃣ 동적으로 list 변경
① 변수 추가
const [list, setList] = useState([{id:1, name:"길동"},{id:2, name:"꺽정"}]);
return (
<div>
{list.map((user)=><h1>{user.name}</h1>)}
</div>
);
② 배열로 ref에 값 넣기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let nums = Array.from({length:5}).map(()=>5);
</script>
</body>
</html>
const myRefs = Array.from({length:list.length}).map(()=>createRef());
return (
<div>
{list.map((user,index)=><h1 ref={myRefs[index]}>{user.name}</h1>)}
</div>
)
③ 길동의 컬러 변경 [0]
myRefs[0].current.style.backgroundColor='red';