petitviolet blog

    Show filter input if applyable records exist in ReactAdmin

    2022-12-29

    ReactReactAdmin

    React Admin provides a capability to filter records shown in a list.

    https://marmelab.com/react-admin/FilteringTutorial.html

    Basically, the combo of ReferenceInput and SelectInput works when applying a filter based on referenced resources. However, it sometimes need to switch visibility of filters when appliable data don't exist since it's possible confusing.

    The below snippet implements it briefly.

    myfilter.tsx
    const MyFilter = (props: any) => {
      // use `useGetList` of React-Admin to get list of the given resource
      const { data, total, isLoading, isSuccess } = useGetList<AwesomeData>(`${resource_name}`);
      // construct `choices` when appliable data exist
      const choices =
        !isLoading && isSuccess && data && total && total > 0
          ? data.map((data: AwesomeData) => ({
              id: data.id,
              name: data.name,
            }))
          : undefined;
    
      // render a filter when choices is available
      return (
        <Filter {...props}>
          {choices && (
            <SelectInput
              source="awesome_data"
              emptyText={'no filter'}
              alwaysOn
              label="Filter by Data"
              choices={choices}
            />
          )}
        </Filter>
      );
    };
    

    This can't be done with using RefernceInput and SelectInput since ReferenceInput is always visible even though there is no referenced resource.