Troubleshooting a ForwardRef issue in a TypeScript and React Native project

Encountering a ts error while using forwardRef.

// [ts] Property 'forwardRef' does not exist on type 'typeof React'.
const MyComponent = React.forwardRef((props: Props, ref: any) => ...

An issue arises in React Native when the parent component throws this error:

Invariant Violation: Element type is invalid: expected a string (for build-in components) or a class/function (for composite components) but got: object

Any suggestions for resolving this dilemma?

Answer №1

As outlined in the definitions:

function forwardRef<T, P = {}>(Component: RefForwardingComponent<T, P>): ComponentType<P & ClassAttributes<T>>;
interface RefForwardingComponent<T, P = {}> {
    (props: P & { children?: ReactNode }, ref?: Ref<T>): ReactElement<any> | null;
    propTypes?: ValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

The argument ref is optional, you can try the following:

To create a ref object within a class with your desired target type (div or View in react-native), use:

private divRef: React.RefObject<div> = React.createRef();

In the props interface for the forwarded component, expose it as an optional property:

interface Props {
  ref?: React.RefObject<div>;
}

Define the forwarded component using React.ComponentType:

const ComponentWithForwardedRef: React.ComponentType<Props> = 
  React.forwardRef((props: Props, ref?: React.Ref<div>) => (
    <div ref={ref}>{props.message}</div>
  ));

When creating an instance of the component with the forwarded ref, pass the created ref object as a prop:

<ComponentWithForwardedRef ref={this.divRef} />

Alternatively, bring everything together into one place:

import * as React from "react";
import { render } from "react-dom";

interface Props {
  message: string;
  ref?: React.RefObject<div>;
}

const ComponentWithForwardedRef: React.ComponentType<Props> = 
  React.forwardRef((props: Props, ref?: React.Ref<div>) => (
    <div ref={ref}>{props.message}</div>
  ));

class App extends React.Component<Props> {
  private divRef: React.RefObject<div> = React.createRef();

  public componentDidMount() {
    const div = this.divRef.current;
    // Check the console!
    console.log(div);
  }

  public render() {
    return (
      <ComponentWithForwardedRef ref={this.divRef} {...this.props} />
    )
  }
}

render(<App message="hello world" />, document.getElementById("root"));

Link for future reference: https://codesandbox.io/s/6v152q394k

Dependencies (for reference purposes)

"@types/react": "^16.3.11",
"@types/react-native": "^0.55.19",
"react-native": "0.55.2",
"typescript": "^2.8.1"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Top method for troubleshooting JavaScript code in Visual Studio 2010

Is there a way to troubleshoot JavaScript code in Visual Studio 2010 for MVC Razor projects? ...

Can we access global variables directly in an Angular 2 HTML template?

After setting the app.settings as shown below public static get DateFormat(): string { return 'MM/DD/YYYY';} I need to utilize it in one of my HTML templates for a component. This is what I want to achieve. <input [(ngModel)]="Holiday" [dat ...

Unable to submit form in Node.js with Express

I am just starting out with node.js and I need help with a sample form to insert values into a database. Below is the code snippet for my test page: <form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencode ...

How do you properly perform typechecking on a custom fetch function in ReactQuery? I'm encountering an error that states: "....is of an unknown type."

Currently, I am working with typescript + react-query and creating a custom fetch function. I am struggling to properly type this function and encountering a TypeScript error when attempting to use myQuery.error.message const locationQuery: QueryObserverRe ...

Exploring the Implementation of Multiple Form Validations in SharePoint using PreSaveAction

My knowledge of Javascript is limited to what I can gather from online resources. Currently, I'm facing a challenge with a SharePoint form where I need to set up specific validations that trigger when a user hits the "Save" button. The validations I& ...

Struggling with the compilation of this Typescript code

Encountering a compile error: error TS2339: Property 'waitForElementVisible' does not exist on type 'signinPage' SigninPage code snippet: export class signinPage{ constructor(){ emailInput: { selector: 'input[type ...

Form submissions are not saving checkbox answers

As a beginner, I'm struggling to save the checkbox answers on the page after submission. The code below is quite lengthy (checkboxes start at 314). I have a feeling that I might be missing a piece of code, but I just can't seem to pinpoint what i ...

Intellisense fails to function properly after attempting to import a custom npm package

I've encountered an issue with a custom npm package that I created using storybook. The components function properly in other projects when imported, but the intellisense feature is not working as expected. Interestingly, when I import the same compon ...

"Utilize Regular Expressions to conceal part of a text string with a

Looking for a way to conceal part of a string using JavaScript? For example, wanting to mask the second and third segments of a credit card number like this using regex: 4567 6365 7987 3783 → 4567 **** **** 3783 3457 732837 82372 → 3457 ****** 82372 ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

Using React-Native on Android: Sending an Object as a Property to Native Android User Interface Component

Currently in the process of developing a Native UI component for my React-Native Android application using Java. Encountering a challenge with transferring a detailed object as a requirement for rendering the said component. I am wondering if there exists ...

How can we use SWR to fetch user data conditionally based on their logged-in state?

I am facing an issue with setting the UI state based on whether a user is logged in or not. The UI should display different states accordingly. I am currently using SSG for page generation and SWR for user data retrieval. However, I noticed that when call ...

Utilizing Leaflet-geotiff in an Angular 6 Environment

I'm currently facing an issue where I am unable to display any .tif image on my map using the leaflet-geotiff plugin. I downloaded a file from gis-lab.info (you can download it from this link) and attempted to add it to my map, but I keep encountering ...

Sending a request in Vue.js and not receiving a defined response

As a beginner in VueJs and Expressjs, my goal is to create the frontend using Vuejs and backend using ExpressJs. When I send a post request to the backend (ExpressJs), I encounter the following issues: 1- Response from the server is undefined. 2- In Chrom ...

The error encountered is due to an invalid assignment on the left-hand side

I'm encountering the error below: Uncaught ReferenceError: Invalid left-hand side in assignment This is the problematic code: if (!oPrismaticMaterial = "") { for (var i = 0; i < oPrismaticMaterial.length; i++) { if (oPrismaticMater ...

What is the best way to store JSON encoded items in an array using square brackets?

Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue whe ...

Javascript retrieve the style of an element in every possible state

I am interested in retrieving the line height of an element; it's a simple task. Here is a method that I know works: console.log(document.getElementById("myDiv").style.lineHeight); console.log($("#myDiv").css('lineHeight')) ...

The addition operator cannot be used with the Number type and the value of 1

Encountering an issue where the operator '+' cannot be applied to types 'Number' and '1' buildQuerySpec() { return { PageSize: this.paging.PageCount, CurrentPage: this.paging.PageIndex + 1, MaxSize: '' ...

WebpackError: The global object "document" could not be found

I am encountering an issue with my website build using gatsby.js and bulma. While building the site, I receive the following error message: WebpackError: document is not defined The only instance where I use document is for the navbar-burger toggle code ...

Navigating through playlists on Ionic

Having just started exploring Ionic, I find myself in need of assistance with regards to navigation. I kicked off the project utilizing the sidemenus starter template which is a basic structure displaying items in a playlist using a playlist control. Howev ...