Skip to content

Instantly share code, notes, and snippets.

@jonbretman
Created August 19, 2018 13:38
Show Gist options
  • Select an option

  • Save jonbretman/f6ace44c94638c2eef24328b519b3dfc to your computer and use it in GitHub Desktop.

Select an option

Save jonbretman/f6ace44c94638c2eef24328b519b3dfc to your computer and use it in GitHub Desktop.

Revisions

  1. jonbretman created this gist Aug 19, 2018.
    61 changes: 61 additions & 0 deletions connectedComponents.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    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');
    }}
    />
    );
    }