React Router - Typescript errors on withRouter after updating version
Here is how I usually strucutre my typed React components:
// These props are provided when creating the component
interface OwnProps {
// ...
}
// These props are provided via connecting the component to the store
interface StateProps {
// ...
}
// These props are provided by the router
interface PathProps {
// ...
}
class Component extends React.Component<OwnProps & StateProps & RouteComponentProps<PathProps>> {
// ...
}
const mapStateToProps = (state: State, props: OwnProps): StateProps => ({
// ...
});
export default withRouter(
connect(mapStateToProps)(Component)
);
I have to solve it like this:
import * as React from 'react';
import { RouteComponentProps, withRouter } from 'react-router-dom';
interface IProps extends RouteComponentProps<any> {
title: string;
}
class MyComp extends React.Component<IProps> {
public render(){
return (
<h1>{this.props.title}</h1>
)
}
}
export default withRouter<IProps>(MyComp);
I just upgraded to TypeScript 2.6 and got same issue.
I managed to resolve it by using RouteComponentProps
.
For URL http://localhost:8080/your-component/abc
and route
<Route component={YourComponent} path="/your-component/:param1?" />
Component should look like this:
import * as React from 'react'
import { withRouter } from 'react-router-dom';
import {RouteComponentProps} from "react-router";
// Type whatever you expect in 'this.props.match.params.*'
type PathParamsType = {
param1: string,
}
// Your component own properties
type PropsType = RouteComponentProps<PathParamsType> & {
someString: string,
}
class YourComponent extends React.Component<PropsType> {
render() {
console.log(this.props); // Prints all props including routing-related
console.log(this.props.match.params.param1); // Prints 'abc'
console.log(typeof this.props.match.params.param1 === 'string'); // prints 'true'
return <div>...</div>;
}
}
export default withRouter(YourComponent);
Here's a functional react approach I use
import { RouteComponentProps } from "react-router";
interface Props extends RouteComponentProps {
thing: Thing | false;
onAction?: () => void;
}
export default withRouter(({ thing, onAction, history }: Props) => {