Created
April 18, 2021 09:12
-
-
Save ruucm/2d577cc40d6220342cbaffb92b60ab54 to your computer and use it in GitHub Desktop.
A simple custom hook to get element's ref.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A simple custom hook to get element's ref. | |
* @example | |
* import { useElement } from "./useElement"; | |
* | |
* export function Test() { | |
* const [ref, element] = useElement(); | |
* | |
* return ( | |
* <div ref={ref}>Test {element && element.getBoundingClientRect().width}</div> | |
* ); | |
* } | |
*/ | |
import { useState, useCallback } from "react"; | |
export function useElement() { | |
const [element, setElement] = useState(null); | |
const ref = useCallback((node) => { | |
setElement(node); | |
}, []); | |
return [ref, element]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment