๐Ÿ“Œ๋ฌธ์ œ1. Navbar list๋ฅผ ํด๋ฆญํ•˜๋ฉด ํ•ด๋‹นํ•˜๋Š” section์œผ๋กœ scroll์ด๋™ ์ด๋ฒคํŠธ๋ฅผ ์ฃผ๊ณ  ์‹ถ์—ˆ๋‹ค. window.scroll() ์ด๋ผ๋Š” webAPI๋ฅผ ์ด์šฉํ•˜์˜€๊ณ , ๊ฐ section์˜ offsetY ๊ฐ’์„ ๋ฐ›์•„์™€ top ๊ฐ’์— ๋Œ€์ž…ํ–ˆ๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ๋ชจ๋‹ˆํ„ฐ ํ™”๋ฉด ํฌ๊ธฐ์— ๋”ฐ๋ผ ์œ„์น˜๊ฐ€ ๋ณ€ํ™”ํ•  ๊ฒƒ์ด๊ณ , ์œ ์—ฐํ•œ ์ฝ”๋“œ๊ฐ€ ์•„๋‹ˆ๋ผ ๊ฐœ์„ ์˜ ํ•„์š”์„ฑ์ด ์žˆ์—ˆ๋‹ค.

๐Ÿ’ซํ•ด๊ฒฐ

UseREF

๊ฐ section components ๋งˆ๋‹ค useRef๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๊ณ , ๊ทธ๊ฒƒ๋“ค์˜ offsetTop ๊ฐ’์„ window.scrollTop({top: offset...}) ๊ฐ’์— ๋„ฃ์–ด์ค€๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์—ฌ๊ธฐ์„œ ๋˜ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.


๐Ÿ“Œ๋ฌธ์ œ2.

Untitled

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

๐Ÿ’ซํ•ด๊ฒฐ

forwardRef

โ†’ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์—์„œ ์ž์‹ ์ปดํฌ๋„ŒํŠธ์˜ DOM์š”์†Œ์— ์ ‘๊ทผํ•  ๋•Œ๋Š” forwardRef๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ ‘๊ทผํ•ด์•ผ ํ•œ๋‹ค.

๐Ÿšฉ

	const aboutSection = useRef(null);
  const projectSection = useRef(null);
  const skillSection = useRef(null);
  const contactSection = useRef(null);
  const scrollToSection = (elementRef) => {
    if (elementRef.current !== null) {
      const offset = elementRef.current.offsetTop;
      window.scrollTo({
        top: offset - 100,
        behavior: "smooth",
      });
    }
  };

return (
    <div>
      <Navbar
        scrollToSection={scrollToSection}
        aboutSection={aboutSection}
        projectSection={projectSection}
        skillSection={skillSection}
        contactSection={contactSection}
      />

section component ๋งˆ๋‹ค ref ์†์„ฑ์„ ๋„ฃ์–ด์ฃผ๊ณ , ๊ทธ ํ•ด๋‹น DOM์˜ offsetTop์„ offset ๋ณ€์ˆ˜์— ํ• ๋‹นํ–ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ฐ๊ฐ์˜ component๋กœ ๊ฐ€์„œ forwardRef๋กœ ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ณด๋‚ด์ค€ ref๋ฅผ ๋ฐ›๋Š”๋‹ค.

๐Ÿšฉ