0

I am new to React and I am trying to convert this code below to a function component, but it doesn't work, I have never used class components. Could anyone help me to convert it? Thanks in advance.

import React from 'react'
import ReactDOM from 'react-dom'
import ScrollSnap from 'scroll-snap'

import './styles.css'

class App extends React.Component {
  container = React.createRef()

  bindScrollSnap() {
    const element = this.container.current
    new ScrollSnap(element, {
      snapDestinationY: '90%',
    }).bind()
  }

  componentDidMount() {
    this.bindScrollSnap()
  }

  render() {
    return (
      <div ref={this.container}>
      </div>
 )
}
Myrat
  • 347
  • 2
  • 4
  • 16

1 Answers1

0

Here's what you need to do:

  1. Replace createRef with useRef which is the functional hook to be used in functional components.
  2. Replace componentDidMount with useEffect() with an empty array as dependency array, which basically runs that code once, on mount.
const App = () => {
  const containerRef = React.useRef(null);

  const bindScrollSnap = () => {
    new ScrollSnap(containerRef , {
      snapDestinationY: '90%',
    }).bind()
  }
  React.useEffect(() => {
    bindScrollSnap();
  }, []);
  return <div ref={containerRef}></div>
}
bamtheboozle
  • 5,847
  • 2
  • 17
  • 31
  • `TypeError: this.listenerElement.addEventListener is not a function` gives exactly the same error which I got when I tried to convert it too. Here is the entire code: ` const containerRef = React.useRef(null); const bindScrollSnap = () => { new ScrollSnap(containerRef, { snapDestinationY: "90%", }).bind(); }; React.useEffect(() => { bindScrollSnap(); }, []); return (
    ); }; export default App; `
    – Myrat Dec 02 '21 at 11:45
  • `scroll-snap` expects an element not a ref. try to find a different library that works with react – bamtheboozle Dec 02 '21 at 12:04
  • Yeah, I have found another library. Thanks anyway. – Myrat Dec 02 '21 at 12:15