Setting up a Property Grid component for Unified Selection

As described in the Property Grid selection handling section, interaction between the Property Grid component and Unified Selection is one way - from Unified Selection to the Property Grid. That means that whenever Unified Selection changes, the content in the Property Grid is reloaded to represent what is selected.

Reference

The Reference section in Unified Selection page describes the core APIs used in Unified Selection workflows.

The @itwin/presentation-components package delivers usePropertyDataProviderWithUnifiedSelection hook to make setting up Property Grid components to work with Unified Selection easier. The hook takes an IPresentationPropertyDataProvider and updates its keys prop whenever Unified Selection changes.

Example

The below example shows how to create a very basic presentation rules driven Property Grid component and hook it into Unified Selection. The latter part is achieved by using usePropertyDataProviderWithUnifiedSelection on the data provider.

function MyPropertyGrid(props: { imodel: IModelConnection }) {
  // create a presentation rules driven data provider; the provider implements `IDisposable`, so we
  // create it through `useOptionalDisposable` hook to make sure it's properly cleaned up
  const dataProvider = useOptionalDisposable(
    useCallback(() => {
      return new PresentationPropertyDataProvider({ imodel: props.imodel });
    }, [props.imodel]),
  );

  if (!dataProvider) {
    return null;
  }

  // render the property grid
  return <MyPropertyGridWithProvider dataProvider={dataProvider} />;
}

function MyPropertyGridWithProvider({ dataProvider }: { dataProvider: PresentationPropertyDataProvider }) {
  // set up the data provider to be notified about changes in unified selection
  const { isOverLimit, numSelectedElements } = usePropertyDataProviderWithUnifiedSelection({ dataProvider });

  // width and height should generally we computed using ResizeObserver API or one of its derivatives
  const [width] = useState(400);
  const [height] = useState(600);

  // data provider is going to be empty if no elements are selected
  if (numSelectedElements === 0) {
    return <>Select an element to see its properties</>;
  }

  // there's little value in loading properties for many elements (see `PropertyDataProviderWithUnifiedSelectionProps.requestedContentInstancesLimit`)
  if (isOverLimit) {
    return <>Please select less elements</>;
  }

  // render the property grid
  return <VirtualizedPropertyGridWithDataProvider dataProvider={dataProvider} width={width} height={height} />;
}

Last Updated: 05 March, 2024