Connected React Router exports types for RouterState
which is great! However I don't see typings for match
. Would assume those could also be imported and added to reducer such as RouterState
is used below and in reducer:
const rootReducer = (history: History) => combineReducers({
count: counterReducer,
router: connectRouter(history)
})
export interface State {
count: number
router: RouterState
}
Without which you can't really use this.props.match
in connected components and such to match params, etc. Is there a workaround here for those using TypeScript who also need to add to reducer? Or am I missing a key part here? Thanks so much!
You have 2 ways to do it.
createMatchSelector
function inside mapStateToProps
to extract match
from your state. DEMOimport * as React from "react";
import { connect } from "react-redux";
import { createMatchSelector } from "connected-react-router";
import { match } from "react-router";
import { State } from "./reducers";
interface StateProps {
match: match<{ name?: string }>;
}
const Hello = (props: StateProps) => (
<div>Hello {props.match.params.name}!</div>
);
const mapStateToProps = (state: State) => {
const matchSelector = createMatchSelector("/hello/:name");
return {
match: matchSelector(state)
};
};
export default connect<StateProps>(
mapStateToProps,
null
)(Hello);
match
directly from router, not from the state. DEMOimport * as React from "react";
import { RouteComponentProps, withRouter } from "react-router";
const Hello = (props: RouteComponentProps<{ name?: string }>) => (
<div>Hello {props.match.params.name}!</div>
);
export default withRouter(Hello);