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