loading...
Cover image for Day 4 of #100DaysOfCode: Scroll event handling and localStorage for React component

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

jenhsuan profile image Jen-Hsuan Hsieh ・1 min read

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>
    )
}

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>
    )
}

That's it!

Implementations

Articles

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

Posted on by:

jenhsuan profile

Jen-Hsuan Hsieh

@jenhsuan

6+ year work experience in the software engineering field. 2+ year work experience with front-end JavaScript framework like React.js, Knockout.js. and Microsoft solution.

Discussion

markdown guide