useRef 개념정리

FrontEnd

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] 이런식으로 출력할 수 있게 해준다

'FrontEnd' 카테고리의 다른 글

props 개념정리(변수,함수 passing하기)  (0) 2022.11.16
components styled 개념정리  (0) 2022.11.16
useMemo 개념정리  (0) 2022.11.16
React UseEffect 개념정리  (0) 2022.11.16
리액트 개념정리  (0) 2022.11.16