DEV Community

Cover image for Day 4 of #100DaysOfCode: Scroll event handling and localStorage for React component
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on

Day 4 of #100DaysOfCode: Scroll event handling and localStorage for React component

Introduction

Today I just want to add common operations in the React component. What I want to do today is to practice the local storage and the windows event.

Register a scroll event

  • We can register the windows event in useEffect hooks.
const Content = () => {
  const [style, setStyle] = useState('sidebar1')
  React.useEffect( ()=>{
    window.addEventListener('scroll', handleScroll);
    }, []);

  const handleScroll = e => {
    const winScroll =
    document.body.scrollTop || document.documentElement.scrollTop
    if(winScroll < 100) {
        setStyle('sidebar1')
    } else {
        setStyle('sidebar1 sidebar2')
    }
  }

    return (
      <Fragment>
        ...
      </Fragment>
    )
}
Enter fullscreen mode Exit fullscreen mode

Local storage

  • Local storage is one of new features of HTML 5. Users can store data in the browser until delete the local storage manually up to 5 MB. One of the differences between cookie and local storage is that the local storage won't be sent to server-side.
  • The format of key and value are string
const Content = () => {
  const [num, setNum] = useState(0)
  const add = e => {
    setNum(num + 1)
    localStorage.setItem('num', num + 1)
  }
  const remove = e => {
    if (num > 0) {
      setNum(num - 1)
      localStorage.setItem('num', num - 1)
    }
  }
  React.useEffect( ()=>{
    var localNum = localStorage.getItem('num')
    if (localNum !== null) {
      setNum(localNum)
    }else{
      setNum(0)
    }  
  }, []);
    return (
      <Fragment>
        <div className={style}>
          ({num}) Menu
         </div>
        <Menu add={add} remove={remove}/>
      </Fragment>
    )
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Implementations

Articles

There are some of my articles. Feel free to check if you like!

Top comments (0)