|
| 1 | +{/* Copyright 2024 Adobe. All rights reserved. |
| 2 | +This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 3 | +you may not use this file except in compliance with the License. You may obtain a copy |
| 4 | +of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 5 | +Unless required by applicable law or agreed to in writing, software distributed under |
| 6 | +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 7 | +OF ANY KIND, either express or implied. See the License for the specific language |
| 8 | +governing permissions and limitations under the License. */} |
| 9 | + |
| 10 | +import {Layout} from '@react-spectrum/docs'; |
| 11 | +export default Layout; |
| 12 | + |
| 13 | +import docs from 'docs:@react-aria/utils'; |
| 14 | +import {HeaderInfo, FunctionAPI, TypeContext, InterfaceType, PageDescription} from '@react-spectrum/docs'; |
| 15 | +import packageData from '@react-aria/utils/package.json'; |
| 16 | + |
| 17 | +--- |
| 18 | +category: Utilities |
| 19 | +keywords: [ref] |
| 20 | +--- |
| 21 | + |
| 22 | +# useObjectRef |
| 23 | + |
| 24 | +<PageDescription>{docs.exports.useObjectRef.description}</PageDescription> |
| 25 | + |
| 26 | +<HeaderInfo |
| 27 | + packageData={packageData} |
| 28 | + componentNames={['useObjectRef']} /> |
| 29 | + |
| 30 | +## API |
| 31 | + |
| 32 | +<FunctionAPI function={docs.exports.useObjectRef} links={docs.links} /> |
| 33 | + |
| 34 | +## Introduction |
| 35 | + |
| 36 | +`useObjectRef` is a utility function that will give an object ref back regardless of if a |
| 37 | +callback ref or object ref was passed in. This is useful for passing refs to React Aria hooks. |
| 38 | + |
| 39 | +## Example |
| 40 | + |
| 41 | +```tsx example |
| 42 | +import {useObjectRef} from '@react-aria/utils'; |
| 43 | +import {useButton} from '@react-aria/button'; |
| 44 | +import {AriaButtonProps} from '@react-types/button'; |
| 45 | + |
| 46 | +let Button = React.forwardRef((props: AriaButtonProps, ref: React.ForwardedRef<HTMLButtonElement>) => { |
| 47 | + let objRef = useObjectRef(ref); |
| 48 | + let {buttonProps} = useButton(props, objRef); |
| 49 | + let {children} = props; |
| 50 | + |
| 51 | + return ( |
| 52 | + <button {...buttonProps} ref={objRef}> |
| 53 | + {children} |
| 54 | + </button> |
| 55 | + ); |
| 56 | +}); |
| 57 | + |
| 58 | +function MyButton(props) { |
| 59 | + let ref = React.useRef(null); |
| 60 | + return <Button ref={ref} onPress={() => console.log(ref.current)}>{props.children}</Button>; |
| 61 | +} |
| 62 | + |
| 63 | +<MyButton>Test</MyButton> |
| 64 | +``` |
0 commit comments