상단 네이게이션 바를 사용할 때 특정 페이지 이동이 아닌 특정 스크롤로 이동하려 할때 scrollTo 보다 좀 더 괜찮은 방법을 찾다 알아낸 createRef
function App() {
const Aboutref = createRef();
const Projectref = createRef();
const Skillref = createRef();
const Contactref = createRef();
const onAboutClick = () => {
Aboutref.current.scrollIntoView({ behavior: "smooth" });
};
const onProjectClick = () => {
Projectref.current.scrollIntoView({ behavior: "smooth" });
};
const onSkillClick = () => {
Skillref.current.scrollIntoView({ behavior: "smooth" });
};
const onContactClick = () => {
Contactref.current.scrollIntoView({ behavior: "smooth" });
};
return (
<>
<Navi
onAboutClick={onAboutClick}
onProjectClick={onProjectClick}
onSkillClick={onSkillClick}
onContactClick={onContactClick}
/>
<Header />
<About ref={Aboutref} />
<Project ref={Projectref} />
<Skill ref={Skillref} />
<Contact ref={Contactref} />
</>
);
}
createRef를 호출해서 ref생성 후 각 섹션 변수에 할당해준다.
const Aboutref = createRef();
const Projectref = createRef();
const Skillref = createRef();
const Contactref = createRef();
네비게이션을 클릭했을 시 이동할 수 있는 함수를 만들어 준다.
scrollIntoView를 사용하여 호출된 요소의 상위컨테이너를 스크롤 하게 한다.
const onAboutClick = () => {
Aboutref.current.scrollIntoView({ behavior: "smooth" });
};
const onProjectClick = () => {
Projectref.current.scrollIntoView({ behavior: "smooth" });
};
const onSkillClick = () => {
Skillref.current.scrollIntoView({ behavior: "smooth" });
};
const onContactClick = () => {
Contactref.current.scrollIntoView({ behavior: "smooth" });
};
Navi 컴포넌트에는 이벤트 함수들 전달해 주고 각 섹션마다 할당해 둔 ref를 전달한다.
return (
<>
<Navi
onAboutClick={onAboutClick}
onProjectClick={onProjectClick}
onSkillClick={onSkillClick}
onContactClick={onContactClick}
/>
<Header />
<About ref={Aboutref} />
<Project ref={Projectref} />
<Skill ref={Skillref} />
<Contact ref={Contactref} />
</>
);
}
About컴포넌트로 와서 forwardRef를 사용하여 전달된 ref를 얻음
forwardRef 내부의 두번째 인자로 ref로 전달함.
이 ref를 최상단 div에서 div ref={ref} 으로 전달함.
사용할 모든 컴포넌트에 이와같이 추가해 줌.
const About = forwardRef((props, ref) => {
return (
<div ref={ref}>
<h1>About</h1>
<div className={classes.aboutWrap}>
<div className={classes.imgWrap}>
<img className={classes.proimg} src={profile} alt="profile image" />
</div>
Navi 컴포넌트에서는 전달된 이벤트 함수들을 onClick 이벤트에 할당해줌.
const Navi = (props) => {
return (
<div className={classes.navi}>
<div onClick={props.onAboutClick}>About</div>
<div onClick={props.onProjectClick}>Project</div>
<div onClick={props.onSkillClick}>Skill</div>
<div onClick={props.onContactClick}>Contact</div>
</div>
);
};
같은 컴포넌트에서 ref를 사용하는 자료는 많았지만 다른 컴포넌트로 ref 전달하는 자료가 생각보다 없어서 힘들었다. 그래도 공식문서를보고 차근차근 하다보니 어찌저찌 되었다. 나중에는 App.jsx에 있는 하드코딩을 좀 효율적으로 바꿀 방법을 생각해 봐야겠다.