React hook to create a ref and listening click outside event of the ref.
import React, { useState, useRef } from 'react'
import { useClickOutsideRef } from 'use-click-outside-ref'
export default () => {
const [collapsed, setCollpased] = useState(false);
const dropdownRef = useClickOutsideRef(() => setCollpased(false));
return (
<div ref={dropdownRef}>
<span onClick={() => setCollpased(!collapsed)}>Toggle</span>
{collapsed && <div className="dropdown" />}
</div>
);
};
import React, { useState, useRef } from 'react'
import { useClickOutside } from 'use-click-outside-ref'
export default () => {
const [collapsed, setCollpased] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
useClickOutside(dropdownRef, () => setCollpased(false));
return (
<div ref={dropdownRef}>
<span onClick={() => setCollpased(!collapsed)}>Toggle</span>
{collapsed && <div className="dropdown" />}
</div>
);
};
return a ref and listen to the click outside event.
callback: function
listening click outside event of an element.
ref: element
callback: function