React, ScrollBox, Ref, 참조
2024. 12. 13. 17:04ㆍ웹 개발
Ref
import React, { useRef } from "react";
...
const inputEl = useRef(null); // ref 참조
...
inputEl.current.focus(); // ref 참조
ScrollBox.jsx
import React, { useRef } from 'react';
const ScrollBox = () => {
const boxRef = useRef(null); // ref 참조
const scrollToBottom = () => {
if (boxRef.current) {
console.info(boxRef.current);
const { scrollHeight, clientHeight } = boxRef.current;
boxRef.current.scrollTop = scrollHeight - clientHeight; // ref 참조
}
};
const style = {
border: '1px solid black',
height: '300px',
width: '300px',
overflow: 'auto',
position: 'relative',
};
const innerStyle = {
width: '100%',
height: '650px',
background: 'linear-gradient(white, black)',
};
return (
<>
<div style={style} ref={boxRef}>
<div style={innerStyle} />
</div>
<button onClick={scrollToBottom}>Bottom</button>
</>
);
};
export default ScrollBox;
https://stackblitz.com/edit/react-basecamp-bqwkjeip?embed=1&file=src%2FScrollBox.jsx
'웹 개발' 카테고리의 다른 글
React, useMemo, useCallback (0) | 2024.12.16 |
---|---|
React, Iteration, 컴포넌트 배열로 반환하기, map (1) | 2024.12.16 |
React, useState, Counter.js (1) | 2024.12.13 |
React, Vite + 리액트 프로젝트 시작하기 (1) | 2024.12.13 |
React, State 사용하기 (0) | 2024.12.11 |