Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

add listener in react

// You can do this:
function App() {
  	return (
      	<div onChange={() => console.log('You clicked me')}>
      	hello!
      	</div>
    )
}

// or...
import {useRef, useEffect} from 'react'

const wrapperRef = useRef(null)

useEffect(() => {
  	function callback() {
      	console.log('You clicked me!')
    }
  
  	wrapperRef.current?.addEventListener('click', callback)
  
  	return () => wrapperRef.current?.removeEventListener('click', callback)
}, [])

function App() {
  	return (
      	<div ref={wrapperRef}>
      	hello!
      	</div>
    )
}
 
PREVIOUS NEXT
Tagged: #add #listener #react
ADD COMMENT
Topic
Name
4+6 =