I'm trying to get the onclick handlers in my navbar to scroll different components into view. I have found a way that works, but I'm getting a warning from react, as well as the code is not looking very clean. I'm hoping someone knows how to solve this is in a more correct way, so that the warning goes away and also keeps the code clean.
I'm going to create a scrollTo on each component, so in the Header.js there will be almost similar calls, with different names only.
Here is the structure of the app:
App.js
const App = () => {
return (
<div>
<Header />
<Banner />
<About />
<Technology />
<Contact />
<Portfolio />
</div>
);
};
Technology.js
const Technology = () => {
return (
<section className="technology">
<div className="heading white">
<h2>Technologies</h2>
<p>Some techno</p>
</div>
</section>
)
}
Header.js (Navbar)
const Header = () => {
let technology;
useEffect(() => {
technology = document.querySelector(".technology");
}, []);
return (
<header>
<p className="logo">Portfolio</p>
<div className="toggle"></div>
<ul>
<li>
<p onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>
Home
</p>
</li>
<li>
<p>About Me</p>
</li>
<li>
<p onClick={() => technology.scrollIntoView({ behavior: "smooth" })}>
Technologies
</p>
</li>
<li>
<p>Contact</p>
</li>
<li>
<p>Projects</p>
</li>
</ul>
</header>
);
};
Here is the warning:
Assignments to the 'technology' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect
To solve this I guess I need to pass it from App.js to Header.js, and get it from each Component to App.js? My googling skills have not been sufficient in solving this unfortunately.
I know there is a library for this in react, but I was hoping to solve this in a more "native" way for now.