Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset filter values in react admin framework?

I have a filter component:

export const PostsFilter = (props) => (
  <Filter {...props}>
    <TextInput label='Post ID' source='id' alwaysOn />
    <TextInput label='User ID' source='user_id' alwaysOn />
  </Filter>
);

I need to add a reset button that will clear input values. I understand that in should be done via dispatching smth to redux. So maybe somebody already solved this problem? Thanks!

like image 863
Sasha Kos Avatar asked Oct 22 '18 09:10

Sasha Kos


Video Answer


3 Answers

There is a setFilters prop in your filter component, you can use it:

export const PostsFilter = (props) => (
  <div>
    <Filter {...props}>
      <TextInput label='Post ID' source='id' alwaysOn />
      <TextInput label='User ID' source='user_id' alwaysOn />
    </Filter>
    <Button onClick={() => props.setFilters({
          id: '',
          user_id: ''
     })}>Clear fields</Button>
  <div>
);
like image 128
Alex Avatar answered Sep 27 '22 16:09

Alex


Unfortunately, setFilters does nothing for me. Here is the solution to the problem:

<FormDataConsumer form={'filterForm'} alwaysOn source='stateId'>
      {({ formData, dispatch, ...rest }) => (
        <ReferenceInput
          resource={props.resource}
          source='stateId'
          reference='states'
          onChange={value => {
            dispatch(change('filterForm', 'districtId', null));
          }}
          allowEmpty>
          <SelectInput optionText='name' />
        </ReferenceInput>
      )}
    </FormDataConsumer>

    {(props.filterValues.stateId || props.filterValues.districtId) && (
      <ReferenceInput
        key={props.filterValues.stateId}
        source='districtId'
        reference='districts'
        filter={{ stateId: props.filterValues.stateId }}
        alwaysOn>
        <SelectInput optionText='name' />
      </ReferenceInput>
    )}
like image 26
Alexander Mayatsky Avatar answered Sep 27 '22 17:09

Alexander Mayatsky


Here's how I created a "Clear Filters" button ("react-admin": "3.10.2").

Extending upon the custom ListActions toolbar example...

import { FilterList } from "@material-ui/icons";
import React from "react";
import {
    Button,
    sanitizeListRestProps,
    TopToolbar
} from "react-admin";

const ListActionsTopToolbar = (props) => {
  const {
    className,
    exporter,
    filters,
    maxResults,
    setFilters,
    ...rest
  } = props;
  return (
    <TopToolbar className={className} {...sanitizeListRestProps(rest)}>
        
        {/* Clear Filters Button */}
      <Button onClick={() => setFilters({})} label="Clear Filters">
        <FilterList />
      </Button>

    </TopToolbar>
  );
};

Traceback: https://github.com/marmelab/react-admin/issues/816#issuecomment-734030723

like image 38
Nick Grealy Avatar answered Sep 27 '22 17:09

Nick Grealy