score:18
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!
Source: stackoverflow.com
Related Query
- How to use forwardRef with FunctionComponent in React Native using TypeScript
- How to use jest.spyOn with React function component using Typescript
- How to use refs in React with Typescript
- Using React forwardRef with Typescript generic JSX arguments
- How to use React with Typescript and SASS
- How to use vw and vh css with React Native
- How to use typescript with the definition of custom styles for a select using react-select
- How to use Material UI custom theme in React with Typescript
- how to use .env file in a react js with typescript project?
- How to use React Native AsyncStorage with Redux?
- How do you correctly use React.lazy() in Typescript to import a react component with a generic type parameter?
- can i use the tsx extension for test files if using react with typescript
- React how to use icon inside Textfield Material-UI with TypeScript
- How to use Refs with Material-ui 4, React 16.8, TypeScript 3.5
- How to User Login With Wordpress using React Native
- How to use Material UI custom variants in React with Typescript
- How to use emotion/styled with React and Typescript
- How to use radium in React typescript (Error: has no properties in common with type 'CSSProperties'. TS2559)?
- How to use React Hook Form with Typescript (Input Component)
- How to use react-datetime with react + typescript (inside tsx)
- How to set up a chrome extension using React and TypeScript with multiple pages and entry points?
- How to use React refs with new Typescript strictPropertyInitialization option?
- How to use useState hook in React with typescript correctly?
- How to use forwardedAs prop with styled-components? Using forwardedAs prop with typescript
- How to use PropTypes with Typescript in React
- How to use WebWorkers in React using Typescript
- How to use React.forwardRef with TypeScript when using different html elements in the render
- How to use mixins with Typescript and React JSX (TSX)
- How to use Typescript with React Router and match
- How to use Font Awesome Icons with Text using ternary operator in React JS?
More Query from same tag
- useState initial value is not set
- How to reuse the same style rule with multiple selectors
- Error: Invalid hook call. function using hooks been called inside a list in class
- I want to download a file from cdn using a tag but it is opening file in browser
- ReactJS instant Search with input
- How to define TypeScript type for object wrapper that has string as a key & React SFC as a value?
- Problem with props.children in typescript useContext
- How do I manage state on a React component that can have state changed from the parent or from events upon it?
- Delay in playing audio (mp3) in iOS 13 safari/chrome browser
- How to close ant design drawer after click in-side the drawer
- React/webpack - How can I host react app on one server and images/fonts on another server?
- React Fetch API Data - Object Undefined
- React Searchbar history push to another page but with a component
- redux react update array after copying array
- Disable scrolling on `<input type=number>` in React
- Getting child properties of a react function component
- npm material-ui-table-edit loader
- React-table how dynamic accessor
- FIXED: NextJS doesn't allow plugin to set change HTML (prevent re-render?)
- sending props via the react-router Link component
- React Router Lazy Component isn't working
- TypeError: cannot read property setState of undefined
- Why when using redux-thunk, the inner function returns something?
- How to keep track of which posts have been liked by a user?
- ThunkAction getting returned by dispatch instead of the Return Type of the ThunkAction
- How to generate a random number code to confirm an email
- Access this.props in imported function
- how to us external api in react
- How to disable inline of a Flexbox
- How to type an object retrieved using useLocation?