I'm trying to make a sticky header by getting DOM element and passing a function to it with componentDidMount, but get an error, that the 'const' is a Unexpected keyword:
component:
class Header extends Component {
componentDidMount(){
window.addEventListener('scroll', () => {
const isTop = window.scrollY > 100,
const nav = document.getElementById('nav');
if (isTop) {
nav.classList.add('scrolled');
}else {
nav.classList.add('scrolled');
}
});
}
componentWillUnmount() {
window.removeEventListener('scroll');
}
render() {
return (<>
<header>
<nav class="nav" id="nav">
<ul class="header-list">
<li>
<img alt='phone' src={phonelogo} />
</li>
<li>123456789</li>
</ul>
<ul class="header-list">
<li>
<img alt='email' src={email} />
</li>
<li>123@gmail.com</li>
</ul>
</nav>
</header>
</>)
};
};
export default Header;
the error:
Line 17:7: Parsing error: Unexpected keyword 'const'
15 | window.addEventListener('scroll', () => {
16 | const isTop = window.scrollY > 100,
> 17 | const nav = document.getElementById('nav');
| ^
18 | if (isTop) {
19 | nav.classList.add('scrolled');
20 | }else {
Though, it's probably better to use React refs, but it's still interesting what is going on here.
You have written:
const isTop = window.scrollY > 100,
const nav = document.getElementById('nav');
You need to replace the comma with a simicolon at the end of line 16. Like so:
const isTop = window.scrollY > 100;
const nav = document.getElementById('nav');
Line 16. You must remove the Comma or else reomve the const on line 17
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.