mario.b
mario.b

Reputation: 175

MGT PeoplePicker selectionChanged event parameter type

I am creating a SPFx web part with React and I am using the Microsoft Graph Toolkit PeoplePicker. It offers a selectionChanged callback. This callback gets passed a parameter of type Event (defined in typescript/lib/lib.dom.d.ts)

export type PeoplePickerProps = {
    // ....
    selectionChanged?: (e: Event) => void;
}

However, according to this documentation I need to access event.target.selectedPeople. But selectedPeople does not exist as property of event.target.

My code looks like this:

import * as React from 'react';
import { PeoplePicker, People } from '@microsoft/mgt-react/dist/es6/spfx';

export const EmployeePicker: React.FC = (): React.ReactElement => {
  const [people, setPeople] = React.useState([]);

  const handleSelectionChanged = (event: Event): void => {
    console.log('Selection changed');
    console.log('event', event);
    setPeople(event.target.selectedPeople);
  };

  return (
    <div>
      <PeoplePicker selectionChanged={handleSelectionChanged} />
      Selected People:
      <People people={people} />
    </div>
  );
};

I'd like to avoid opting out of the type system. (I guess changing the type of event to any would work) And rather know how I can access the event.target.selectedPeople prop using typescripts type system.

Upvotes: 0

Views: 333

Answers (1)

devil_inside
devil_inside

Reputation: 440

You can use event.details too. You can read about it here https://learn.microsoft.com/en-us/graph/toolkit/customize-components/events. For the people picker there will be an array of the currently selected people.

To make it work with typescript you can either use any or do something like event.target["selectedPeople"] or event["details"]. Or you can create a new type like

type PeoplePickerEventTarget = EventTarget & {selectedPeople: IDynamicPerson[]};

I am not sure what the type of the array is, you can replace any with the correct one or just build your own.

And then in the code you can do something like this

<PeoplePicker
  selectionChanged={(e: Event) => {
     const target = e.target as PeoplePickerEventTarget;
        //do something here
  }}
></PeoplePicker>

Upvotes: 1

Related Questions