Accepted answer

forwarding the ref

refs can be really confusing because there are multiple ways to handle them and because people aren't aware of the difference between the ref object (react.mutablerefobject or react.refobject) and the ref value, which is stored on the .current property of the ref object. you've made that mistake here, along with some missing or incorrect typescript types.

useref<t> is a generic hook where the value t tells up what type of value will be stored. we need to tell app that we intend to store something with a coolalert method. actually we'll see later on that we need our ref to be immutable so we we'll use createref<t> instead.

interface myref {
  coolalert(): void;

const mycustomcomponentref = createref<myref>();

when we call onpress, we need to access the current value of the ref object. by adding the generic to createref, typescript already knows that this value is either myref or undefined. we can call coolalert with the optional chaining ?. operator.

onpress={() => mycustomcomponentref.current?.coolalert()}

now we need to do some work on mycustomcomponent. you've erred by assigning it the type react.functioncomponent<mycustomcomponentprops> because a function component doesn't have the knowledge about ref forwarding that we need.

function forwardref<t, p = {}>(component: refforwardingcomponent<t, p>): forwardrefexoticcomponent<propswithoutref<p> & refattributes<t>>;

the type for mycustomcomponent should be that complicated return type from forwardref. but we don't need to assign that type ourselves, we just need to pass the generics t and p to the forwardref function call. t is the type of the ref and p is the type of the props.

const mycustomcomponent = react.forwardref<myref, mycustomcomponentprops>(...

ok so we got rid of all the typescript errors! yay! except...hold up. it doesn't actually do anything. all of that and it still doesn't work. i hate refs. refs are bad.

using the ref

we forwarded the ref to mycustomcomponent, who now has access to the forwarded ref and can attach it to a dom component. but we don't want it attached to the dom element, we want it attached to mycustomcomponent. but we can't really do that.

by default, you may not use the ref attribute on function components because they don’t have instances [docs]

we have to make use of a hook called useimperativehandle which feels like a hack solution and even the docs say "don't do this". yup, i hate refs.

useimperativehandle customizes the instance value that is exposed to parent components when using ref. as always, imperative code using refs should be avoided in most cases. useimperativehandle should be used with forwardref. [docs]

we have to expose our coolalert method through useimperativehandle.

useimperativehandle(ref , () => ({coolalert}));

and now it actually works, finally!

Related Query

More Query from same tag