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:
Why does it refer to "type 'typeof MenuItem'" instead of simply the type of 'MenuItem'?
Is withRouter exclusive to class components or can it also be applied to functional components?
Do I need to use connect() or map Props to State? If so, what is the rationale behind this?
Lastly, how can this issue be resolved?