javascriptreactjsreact-bootstrap-table

Is there a way to use validation on the textFilter of react-bootstrap-table2-filter?


Below is the object I use.

    {
        dataField: "hostname",
        text: "hostName",
        filter: textFilter({
            placeholder: t("hostName"),
            caseSensitive: true,
            delay: 3000,
            onFilter: (filterValue) => console.log("Filter value: ", filterValue)
        }),
    }

I want to achieve validation check before filtering. onFilter property seems to be working only after filtering is done.


Solution

  • Following this implementation of Custom Filter, I was able to implement a validation mechanism before calling filter method. Here is the code in case link breaks.

    import BootstrapTable from 'react-bootstrap-table-next';
    import filterFactory, { textFilter, customFilter } from 'react-bootstrap-table2-filter';
    
    class PriceFilter extends React.Component {
      static propTypes = {
        column: PropTypes.object.isRequired,
        onFilter: PropTypes.func.isRequired
      }
      constructor(props) {
        super(props);
        this.filter = this.filter.bind(this);
        this.getValue = this.getValue.bind(this);
      }
      getValue() {
        return this.input.value;
      }
      filter() {
        this.props.onFilter(this.getValue());
      }
      render() {
        return [
          <input
            key="input"
            ref={ node => this.input = node }
            type="text"
            placeholder="Input price"
          />,
          <button
            key="submit"
            className="btn btn-warning"
            onClick={ this.filter }
          >
            { `Filter ${this.props.column.text}` }
          </button>
        ];
      }
    }
    
    const columns = [{
      dataField: 'id',
      text: 'Product ID'
    }, {
      dataField: 'name',
      text: 'Product Name',
      filter: textFilter()
    }, {
      dataField: 'price',
      text: 'Product Price',
      filter: customFilter(),
      filterRenderer: (onFilter, column) =>
        <PriceFilter onFilter={ onFilter } column={ column } />
    }];
    
    <BootstrapTable keyField='id' data={ products } columns={ columns } filter={ filterFactory() } />