Menu

gitpiper

useClickInside react Code Snippet in 2024

hookseffecteventintermediate

Last Updated: 1 December 2024

Handles the event of clicking inside the wrapped component.

  • Create a custom hook that takes a ref and a callback to handle the 'click' event.
  • Use the useEffect() hook to append and clean up the click event.
  • Use the useRef() hook to create a ref for your click component and pass it to the useClickInside hook.
const useClickInside = (ref, callback) => { const handleClick = e => { if (ref.current && ref.current.contains(e.target)) { callback(); } }; React.useEffect(() => { document.addEventListener('click', handleClick); return () => { document.removeEventListener('click', handleClick); }; }); };
const ClickBox = ({ onClickInside }) => { const clickRef = React.useRef(); useClickInside(clickRef, onClickInside); return ( <div className="click-box" ref={clickRef} style={{ border: '2px dashed orangered', height: 200, width: 400, display: 'flex', justifyContent: 'center', alignItems: 'center' }} > <p>Click inside this element</p> </div> ); }; ReactDOM.render( <ClickBox onClickInside={() => alert('click inside')} />, document.getElementById('root') );

react snippet similar to useClickInside For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️