Skip to content

Instantly share code, notes, and snippets.

@jonbretman
Created August 19, 2018 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonbretman/f6ace44c94638c2eef24328b519b3dfc to your computer and use it in GitHub Desktop.
Save jonbretman/f6ace44c94638c2eef24328b519b3dfc to your computer and use it in GitHub Desktop.
Typescript connected components example
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