score:46
there are two kinds of refs in modern react: ref objects, and ref callbacks. ref objects are what's created by useref
(or in class components, createref
): it's an object with a current
property. in typescript, these have the type refobject<t>
, where t
is whatever value(s) will be on current
.
ref callbacks are another option, which are needed for some advanced cases. you pass a function into the element, and the function will be called back when the instance is created or destroyed. these have the type (instance: t) => void
.
a shorthand which combines both the ref object and the ref callback into a single type is ref<t>
, and it looks like that's what your code expects. since you haven't shown that code, i'll have to make some educated guesses about it looks like. suppose you have a component which accepts a ref as a prop (perhaps so it can then hand it off to one of its internal components):
interface exampleprops {
buttonref: ref<htmlbuttonelement>
}
const example: fc<exampleprops> = ({ buttonref }) => {
return (
<div>
<button ref={buttonref}>hello</button>
<div>
)
}
since i've defined the prop to be a ref, it can be passed in either a ref object, or a ref callback. that's fine in this case, since i'm not doing anything with it except passing it on to the button. but if i try to write some code to interact with it, i can't assume it to be an object or a function.
if i need to do this, perhaps i could restrict the prop so it only takes ref objects, and then i can assume it will have .current
interface exampleprops {
buttonref: refobject<htmlbuttonelement>
}
const example: fc<exampleprops> = ({ buttonref }) => {
useeffect(() => {
console.log(buttonref.current);
});
return (
<div>
<button ref={buttonref}>hello</button>
<div>
)
}
but maybe i don't want to restrict the way my component can be used, but i still need to be able to interact with the ref somehow. in that case, i'll probably need to make a callback ref of my own, and then add logic to it to handle both my use of the ref, and the prop's use of the ref:
interface exampleprops {
buttonref: ref<htmlbuttonelement>
}
const example: fc<exampleprops> = ({ buttonref }) => {
const myref = useref<htmlbuttonelement>(null);
useeffect(() => {
console.log(myref.current);
});
return (
<div>
<button ref={(element) => {
(myref as mutablerefobject<htmlbuttonelement>).current = element;
if (typeof buttonref === 'function') {
buttonref(element);
} else {
buttonref.current = element;
}
}}>hello</button>
<div>
)
}
the type assertion of as mutablerefobject<htmlbuttonelement>
is needed because myref
is marked as being immutable. this type reflects the fact that only react is supposed to modify the .current
property. that's good for normal use cases, but since we're taking over that responsibility from react, it's ok to change the value.
Source: stackoverflow.com
Related Query
- Property 'current' does not exist on type '((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement>'
- Property 'value' does not exist on type 'Readonly<{}>'
- TypeScript error: Property 'X' does not exist on type 'Window'
- typescript + react/redux: property "yyy" does not exist on type 'intrinsicattributes & intrinsicclassattributes
- Typescript complains Property does not exist on type 'JSX.IntrinsicElements' when using React.createClass?
- error TS2339: Property 'for' does not exist on type 'HTMLProps<HTMLLabelElement>'
- TypeScript error after upgrading version 4 useParams () from react-router-dom Property 'sumParams' does not exist on type '{}'
- Property 'exact' does not exist on type
- Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'
- Trigger click in Typescript - Property 'click' does not exist on type 'Element'
- Property does not exist on type 'DetailedHTMLProps, HTMLDivElement>' with React 16
- TS2339: Property 'tsReducer' does not exist on type 'DefaultRootState'
- Property ... does not exist on type 'IntrinsicAttributes & ...'
- Property 'XYZ' does not exist on type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'
- Property 'hot' does not exist on type 'NodeModule'.ts(2339)
- TS2339: Property 'props' does not exist on type 'Home'
- TypeScript error: Property 'children' does not exist on type 'ReactNode'
- TypeScript error: Property 'scrollIntoView' does not exist on type 'never'. TS2339
- Property 'value' does not exist on type 'never'. when use useRef hook in mui
- ts(2322) Property children does not exist on type 'Intrinsic attributes and Props'
- Property does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'
- Generics error with forwardRef: Property 'ref' does not exist on type 'IntrinsicAttributes'
- In ReactJS trying to get params but I get property 'id' does not exist on type '{}'
- Property "value" does not exist on type Readonly
- Typescript Error: TS2339: Property 'span' does not exist on type 'JSX.IntrinsicElements'
- ReactJS TS, Property 'match' does not exist on type 'Readonly<{children?:ReactNode}> & Readonly<MyProps>'
- useRef Typescript error: Property 'current' does not exist on type 'HTMLElement'
- React with Typescript: Property 'push' does not exist on type 'History'
- Property 'state' does not exist on type 'FetchPeriod'
- Property 'y' does not exist on type 'DefaultRootState'
More Query from same tag
- How to fit one div into another div of a modal
- How to get the value of variable to change the css of body/root element in reactJS?
- React Redux- My action creator is not passing actions to reducer (sync)
- Pluggable Keycloak-JS for Frontend Development
- React: Rendering second functional component when the first one is updated
- Resolve SCSS File in Webpack Modules
- How can I render Html with script tag in my React Component?
- "startIndex" of Recharts Brush does not change even though using setState and state was changed
- how generate options for select component dynamically with ant design
- How to validate my input field based on formula
- Force React to fire event through injected JavaScript
- In React how do you check if at least one checkbox has been selected
- How to add Normalize CSS to Storybook?
- React Flux - dispatching within a dispatch - how to avoid?
- React Tic Tac Toe tutorial: can you explain how a number is passed as an argument to the function of the click event?
- Undefined State when pulling data for mount
- Render a component from array after taking input in react
- how to delay checking redux store when authenticating using Higher Order Components
- Leaflet _ ReactJS - Where to find the invalidateSize property?
- Hide complete text if it overflows
- Typescript function parameter has two types, and the property of one type can't be accessed because it is not a property of the other type
- React-Redux mapStateToProps value is undefined after being set by reducer
- If props is missing Should I use memo?
- How to update data in mongodb database and show in ui
- How to set nextjs router query parameter
- Remove (or at least hide) card on react-admin List
- How to handle error format in Redux-toolkit rtk-query graphql application
- Check type of React component
- Nextjs assets 404 Not Found when using dynamic rouitng while ssr
- combining useState with pop()