Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connected React Router and TypeScript for `match`

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:

https://github.com/supasate/connected-react-router/blob/master/examples/typescript/src/reducers/index.ts#L13

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!

like image 330
Bess Avatar asked Jan 27 '23 09:01

Bess


1 Answers

You have 2 ways to do it.

  1. You can use createMatchSelector function inside mapStateToProps to extract match from your state. DEMO
import * 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);
  1. You can get match directly from router, not from the state. DEMO
import * 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);
like image 66
teimurjan Avatar answered Jan 30 '23 14:01

teimurjan