I am trying to not write this function for every section and modularize it by passing in a string (the ID of the section), however, the function seems to run before the click. The section comes back as ‘projects’ if I console it out, but this is before the click and an error pops up: “TypeError: Cannot read property ‘scrollIntoView’ of null”
Any idea how I can make this work? (Ignore the inline styling.)
import React from 'react'
const Navbar = () => {
const scrollToSection = (section) => {
document.getElementById(section).scrollIntoView({ behavior: "smooth" })
}
return (
<section>
<h1>Navbar</h1>
<nav
style={{
display: 'flex',
justifyContent: 'space-evenly',
cursor: 'pointer',
}}
>
<span>Home</span>
<span>About</span>
<span onClick={scrollToSection('projects')}>Portfolio</span>
<span>Contact</span>
</nav>
</section>
)
}
export default Navbar