I was trying yo create a scroll effet when you click on the options we get to go toa specific section, Why I am getting this error ??
import React, { useRef } from 'react'
import home from './home.css'
import video from './A.mp4';
import img1 from './home1.jpeg';
import img2 from './home4.jpeg';
import img3 from './home3.jpeg';
export default function Home() {
const about = useRef(null);
const work = useRef(null);
const contact = useRef(null);
const scrollSection = (elementRef) => {
window.scrollTo({
top: elementRef.current.offsetTop,
behavior: "smooth",
});
};
return (
<>
<div ref={about} className='first'>
<nav className="navbar">
<div className="logo">
<video loop autoPlay muted playsInline className='logo_video' >
<source src={video} type="video/mp4" />
</video>
</div>
<div className="about_section">
<ul className="list">
<li className="info about">
<div className="number">1.
</div>
<div className="infoindex" onClick={() => scrollSection(about)}>
About
</div>
</li>
<li className="info">
<div className="number">2.
</div>
<div className="infoindex" onClick={scrollSection(work)}>
Work
</div>
</li>
<li className="info">
<div className="number">3.
</div>
<div className="infoindex" onClick={scrollSection(contact)}>
Contact
</div>
</li>
</ul>
{/* <div className="hamburger">
<div className="horline"></div>
<div className="horline"></div>
<div className="horline"></div>
</div> */}
</div>
</nav>
This is the code I am dealing with,
Random text Random text Random text Random text Random text Random text Random text Random text Random text Random text Random text Random text Random text
>Solution :
Take a look to the following lines of code:
<div className="infoindex" onClick={() => scrollSection(about)}>
<div className="infoindex" onClick={scrollSection(work)}>
<div className="infoindex" onClick={scrollSection(contact)}>
Now you can see the difference, scrollSection(work) and scrollSection(contact) are triggering the scrollSection function in each render even if you don’t click them. Don’t forget to add the arrow function to them.
<div className="infoindex" onClick={() => scrollSection(about)}>
<div className="infoindex" onClick={() => scrollSection(work)}>
<div className="infoindex" onClick={() => scrollSection(contact)}>
By the way, you are only handling the about reference at the div parent:
<div ref={about} className='first'>
You need to handle the rest of references too and don’t forget the onClick event, if your about div wrapps the rest of divs, then it could have unwanted behaviors if you want to click the child divs inside the parent div.