Utilities & Refs
useEventListenerRef
About
A react hook to add an event listener to a ref
Examples
Basic usage
import { useState } from "react";
import { useEventListenerRef } from "rooks";
import "./styles.css";
export default function App() {
const [value, setValue] = useState(0);
const ref = useEventListenerRef("click", function() {
setValue(value + 1);
});
return (
<div
ref={ref}
className="App"
style={{
padding: "20px",
border: "5px solid dodgerblue",
}}
>
<h2>Click in this box</h2>
<p> Value is {value}</p>
</div>
);
}Arguments
| Arguments | Type | Description | Default value |
|---|---|---|---|
| eventName | string | The event to track | undefined |
| callback | Function | The callback to be called on event | () => void |
| conditions | object | The options to be passed to the event listener | |
| isLayoutEffect | boolean | Should it use layout effect. Defaults to false | false |
Return
| Return value | Type | Description |
|---|---|---|
| ref | Function | A callback ref that can be used as ref prop |