Skip to content

Instantly share code, notes, and snippets.

@JaSpr
Last active March 5, 2021 19:50
Show Gist options
  • Save JaSpr/502084fd5989b53760d93148cf67d864 to your computer and use it in GitHub Desktop.
Save JaSpr/502084fd5989b53760d93148cf67d864 to your computer and use it in GitHub Desktop.
Creating typescript components for react-redux connect
import * as React from 'react';
import { connect, MapDispatchToProps, MapStateToProps } from 'react-redux';
interface OwnProps { // Props that will be passed in via JSX when mounting a Header node
// ...
}
interface ConnectStateProps { // props that will come from mapStateToProps
displayName: string;
isAuthenticated: boolean;
}
interface ConnectDispatchProps { // props that come from mapDispatchToProps
logIn?: () => void;
logOut?: () => void;
}
interface State {}
type HeaderProps = OwnProps & ConnectStateProps & ConnectDispatchProps;
class Header extends React.Component<HeaderProps, State> {
render() {/*...*/}
}
// the three types used in the MapStateToProps generic are (1) what we're mapping TO props, (2) what this component will still need to get from JSX, and (3) global state's type
type ConnectStateMapper: MapStateToProps<ConnectStateProps, OwnProps, AppState>
const mapStateToProps: ConnectStateMapper = (state) => {/*...*/}
// the TWO types used in the MapDispatchToProps generic are (1) what we're mapping TO props, (2) what this component will still need to get from JSX
type ConnectDispatchMapper: MapDispatchToProps<ConnectDispatchProps, OwnProps>
const mapDispathToProps: ConnectDispathMapper = (dispatch) => {/*...*/}
export default connect(mapStateToProps, mapDispatchToProps)(Header);
@Rahul-Sagore
Copy link

On line no. 35, should it be ConnectDispatchMapper instead of ConnectDispathMapper?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment