Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected keyword 'const' in componentDidMount, React

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>[email protected]</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.

like image 587
Gustė Avatar asked Oct 24 '25 01:10

Gustė


2 Answers

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');
like image 98
Bram Avatar answered Oct 26 '25 15:10

Bram


Line 16. You must remove the Comma or else reomve the const on line 17