javascriptreactjsnext.jsstyled-jsx

Why the variable in styled-jsx tag didn't work?


The div component is not fixed, but the sticky variable is true. Why?

import React, { useEffect } from 'react'

export default function Navbar(props) {

  const DESKTOP_Y = 250
  const MOBILE_Y = DESKTOP_Y / 2

  let sticky = false

  const handleScroll = () => {
    console.log(window.innerWidth + ' ' + window.scrollY + ' ' + sticky)
    if (window.innerWidth > 850) {
      if (window.scrollY > DESKTOP_Y) {
        sticky = true
      } else {
        sticky = false
      }
    } else if (window.innerWidth < 850) {
      if (window.scrollY > MOBILE_Y) {
        sticky = true
      } else {
        sticky = false
      }
    }
  }

  useEffect(() => {
    window.addEventListener('scroll', handleScroll)
    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [])

  return (
    <nav>
      <div>Pozdro</div>
      <style jsx>
        {`
          div {
            ${sticky ? 'position: fixed' : ''}
          }
        `}
      </style>
    </nav>
  )
}

Solution

  • Setting sticky will not actually update your component. Try using react hooks to keep track of state:

    sticky, setSticky = useState(0);
    const handleScroll = () => {
    console.log(window.innerWidth + ' ' + window.scrollY + ' ' + sticky)
    if (window.innerWidth > 850) {
      if (window.scrollY > DESKTOP_Y) {
        setsticky(true);
      } else {
        setsticky(false);
      }
    } else if (window.innerWidth < 850) {
      if (window.scrollY > MOBILE_Y) {
           setsticky(true);
      } else {
           setsticky(false);
      }
    }