Troubleshooting type conflicts while utilizing the 'withRouter' function in Typescript

Currently, I am delving deeper into React and TypeScript, seeking to expand my understanding and practical experience. While utilizing withRouter from react-router-dom, I encountered a typing error.

The issue arose within my simplistic code snippet. I attempted to research similar problems, but the responses varied. Some indicated a potential upgrade error (albeit from 2016), while others referenced using a connect() statement. However, I am not utilizing connect(), which prompted the question of whether my approach is incorrect. Suggestions also mentioned mapping Props to State, a concept I have not encountered before. I am hopeful that someone can offer guidance on what I might be overlooking and what areas I should further explore.

The code snippet is as follows:

import React from "react";
import { withRouter } from "react-router-dom";

interface ISection {
  id: number;
  title: string;
  imageUrl: string;
  size: string;
}

class MenuItem extends React.Component<ISection> {
  render() {
    return (
      <div className={`${this.props.size} menu-item`}>
        <div
          className="background-image"
          style={{ backgroundImage: `url(${this.props.imageUrl})` }}
        />
        <div className="content">
          <h1 className="title">{this.props.title}</h1>
          <span className="subtitle">some subtitle</span>
        </div>
      </div>
    );
  }
}

export default withRouter(MenuItem);

Expectations entailed seamless functionality; I initially attempted a functional component due to the absence of state. However, all solutions I encountered pointed towards using a class component. Consequently, I transitioned to a class component, yet I encounter the following error with the MenuItem in the final line:

Argument of type 'typeof MenuItem' is not assignable to parameter of type 'ComponentClass<RouteComponentProps<any, StaticContext, any>, any> | FunctionComponent<RouteComponentProps<any, StaticContext, any>> | (FunctionComponent<RouteComponentProps<any, StaticContext, any>> & ComponentClass<...>) | (ComponentClass<...> & FunctionComponent<...>)'.
  Type 'typeof MenuItem' is not assignable to type 'ComponentClass<RouteComponentProps<any, StaticContext, any>, any>'.
    Types of parameters 'props' and 'props' are incompatible.
      Type 'RouteComponentProps<any, StaticContext, any>' is missing the following properties from type 'Readonly<ISection>': id, title, imageUrl, sizets(2345)

My queries are:

  1. Why does it refer to "type 'typeof MenuItem'" instead of simply the type of 'MenuItem'?

  2. Is withRouter exclusive to class components or can it also be applied to functional components?

  3. Do I need to use connect() or map Props to State? If so, what is the rationale behind this?

  4. Lastly, how can this issue be resolved?

Answer №1

According to the documentation, the `withRouter` function will update the `match`, `location`, and `history` props of the wrapped component whenever it renders.

Therefore, the `MenuItem` component needs to have props to receive these router props. However, at the moment, the `MenuItem` component only has props of type `ISection`, which does not include router props.

The simplest way to add router props is to combine `ISection` with `RouteComponentProps`.

import { withRouter, RouteComponentProps } from "react-router-dom";

// ...
class MenuItem extends React.Component<ISection & RouteComponentProps> {

The full code example is as follows:

import * as React from 'react';
import { withRouter, RouteComponentProps } from "react-router-dom";

interface ISection {
    id: number;
    title: string;
    imageUrl: string;
    size: string;
}

class MenuItem extends React.Component<ISection & RouteComponentProps> {
    render() {
        return (
            <div className={`${this.props.size} menu-item`}>
                <div
                    className="background-image"
                    style={{ backgroundImage: `url(${this.props.imageUrl})` }}
                />
                <div className="content">
                    <h1 className="title">{this.props.title}</h1>
                    <span className="subtitle">some subtitle</span>
                </div>
            </div>
        );
    }
}

export default withRouter(MenuItem);

Answers to the questions raised:

  1. Why does it say "type 'typeof MenuItem'"? Shouldn't it just say the type of 'MenuItem' instead of the function to obtain the type?

    The error arises from types incompatibility. `MenuItem` is a class, not a type. To get the type of `MenuItem`, you should use `typeof MenuItem`. Therefore, `typeof MenuItem` is the correct type, as indicated by the compiler.

  2. Is it necessary for withRouter to work with class components, or does it also work on functional components?

    `withRouter` can work with both class components and functional components. A functional component implementation is provided below:

    const Cmp1: React.FunctionComponent<ISection & RouteComponentProps> = (props) => {
        return (
            <div className={`${props.size} menu-item`}>
                <div
                    className="background-image"
                    style={{ backgroundImage: `url(${props.imageUrl})` }}
                />
                <div className="content">
                    <h1 className="title">{props.title}</h1>
                    <span className="subtitle">some subtitle</span>
                </div>
            </div>
        );
    }
    
    const WrappedCmp = withRouter(Cmp1);
    
  3. Do I need to `connect()` something, or map Props onto State? If so, why?

    No, it's not a strict requirement. `connect` is part of Redux, so if you are using Redux, you can connect. Refer to the documentation for how to use `withRouter` with `connect`, although it's not mandatory.

  4. Lastly, how can I fix this?

    The solution has already been provided above :-)

Answer №2

If you are looking for guidance on incorporating your props interface with WithRouterProps in Next.js, you can do so by following these steps:

import { WithRouterProps } from "next/dist/client/with-router";

class MenuItem extends React.Component<IProps & WithRouterProps>

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

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

Is it possible to execute user-defined functions dynamically in a Node.js application without having to restart the server

I am exploring the potential for allowing users to insert their own code into a Node application that is running an express server. Here's the scenario: A user clicks 'save' on a form and wants to perform custom business validations. This ...

Issue with TypeScript: Difficulty accessing keys in a recursive manner

I've created a custom type that eliminates any nullish values when working with objects. export type ExcludeNullish<T> = Exclude<T, null | undefined>; export type ExcludeNullishKeys<T> = { [K in keyof T]-?: T[K] extends boolean | ...

What is the best way to initiate multiple processes in Node.js and ensure they finish before proceeding?

When working with Node.js and TypeScript, my goal is to initiate multiple processes using the spawn function. Afterwards, I aim to ensure all of these processes are completed before proceeding to execute any additional commands. ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

Issue with accessing storage in Ionic Storage (Angular)

Currently, I am attempting to utilize Ionic storage for the purpose of saving and loading an authentication token that is necessary for accessing the backend API in my application. However, I am encountering difficulties retrieving the value from storage. ...

Retrieve a prepared response from a TypeORM query

I need to retrieve all the courses assigned to a user with a simple query: There are 2 Tables: students & courses return await this.studentsRepository .createQueryBuilder('s') .leftJoinAndSelect('courses', 'c' ...

I'm having trouble figuring out why this React Router setup is not functioning properly. Can anyone provide any insights

As I delve into react routing practice, I've put together a geography-based web app. Starting off, I configured the router paths: import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { BrowserRo ...

When using TypeORM, make sure to include the "WHERE IN (...)" clause in the query condition only if there is a value associated with it

In my TypeScript node.js project using TypeORM (v0.2.40), I have a query to find a record in the database based on specific criteria: userRepository.find({ where: { firstName: 'John', company: 'foo' } }); This executes the following SQ ...

Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array. this.data = [{ label: 'Total', count: details.request.length, }, { label: 'In-Progress', count: details.request.filter((obj) => obj.statusId === 0 || ob ...

Mastering the art of throwing and managing custom errors from the server to the client side within Next.js

I'm in the process of developing a Next.js application and I am faced with the challenge of transmitting customized error messages from the server to the client side while utilizing Next JS new server-side actions. Although my server-side code is func ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Error encountered: YouCompleteMe is unable to locate the necessary executable 'npm' for the installation of TSServer

While attempting to install YouCompleteMe for vim and enable support for Java and Javascript, I followed the instructions provided here. My command was: sudo /usr/bin/python3.6 ./install.py --java-completer --ts-completer Unfortunately, I encountered an ...

Obtain the filter criteria within the user interface of a Kendo grid

My Kendo grid looks like this: <kendo-grid [data]="gridData" [pageSize]="state.take" [skip]="state.skip" [sort]="state.sort" [filter]="state.filter" filterable="menu" (dataStateChange)="dataStateChange($event)" > In the ...

How can we pass an optional boolean prop in Vue 3?

Currently, I am in the process of developing an application using Vue 3 and TypeScript 4.4, bundled with Vite 2. Within my project, there exists a file named LoginPage.vue containing the following code: <script lang="ts" setup> const props ...

Should I use Object.assign or define class properties?

Currently in the process of developing an angular application that interacts with the twitch API. The API returns data in various formats, some of which I need to parse and save into specific classes. My main concern is understanding the potential drawbac ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...