Created
August 19, 2018 13:38
-
-
Save jonbretman/f6ace44c94638c2eef24328b519b3dfc to your computer and use it in GitHub Desktop.
Typescript connected components example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { connect } from 'react-redux'; | |
// Some example state data | |
interface Person { | |
name: string; | |
} | |
interface State { | |
people: { | |
[key: string]: Person; | |
}; | |
} | |
// the props for Person - note there is no `id` | |
interface PersonProps { | |
person: Person; | |
isActive: boolean; | |
onClick: () => void; | |
} | |
// A Person component - just accepts a Person object so totally unaware of data-fetching | |
const Person = (props: PersonProps) => { | |
return ( | |
<div> | |
{props.person.name} | |
{props.isActive ? ' (Active)' : ''} | |
</div> | |
); | |
}; | |
// Omit<T, K> can be used to create a new type that excludes some keys (specified by K) from T. | |
// See - https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html | |
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; | |
// This type of this functions ownProps defines the type signature of the connected component. | |
// This connected component will accept an `id` prop that can be used to get the Person | |
// from the store state. We need Omit<PersonProps, 'person'> so that the resuling connected | |
// component _doesn't_ need to be passed a `person` prop. | |
function mapStateToProps( | |
state: State, | |
ownProps: { id: string } & Omit<PersonProps, 'person'> | |
) { | |
return { | |
person: state.people[ownProps.id], | |
}; | |
} | |
const ConnectedPerson = connect(mapStateToProps)(Person); | |
function app() { | |
return ( | |
// We can now use the ConnectedComponent as desired | |
<ConnectedPerson | |
id="1234" | |
isActive={true} | |
onClick={() => { | |
console.log('Person clicked'); | |
}} | |
/> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment